package adrspools

import (
	"context"
	"encoding/json"
	"net/http"

	"repository.basistech.ru/BASIS/decort-golang-sdk/internal/constants"
	"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
)

// UpdateRequest struct to update address pool
type UpdateRequest struct {
	// ID of the address pool
	// Required: true
	AddressPoolID string `url:"address_pool_id" json:"address_pool_id" validate:"required"`

	// ID of the version
	// Required: true
	VersionID uint64 `url:"version_id" json:"version_id" validate:"required"`

	// Description of the network
	// Required: true
	Description string `url:"description" json:"description" validate:"required"`

	// Name of the network
	// Required: true
	Name string `url:"name" json:"name" validate:"required"`

	// Network address type
	// Required: true
	NetAddressType string `url:"net_address_type" json:"net_address_type" validate:"required,addressPoolNetTypeValidator"`

	// List of network addresses
	// Required: false
	NetAddresses []UpdateNetAddress `url:"net_addresses,omitempty" json:"net_addresses,omitempty" validate:"dive"`
}

// UpdateNetAddress struct representing network address
type UpdateNetAddress struct {
	// Network address type
	// Required: true
	NetAddressType string `url:"net_address_type" json:"net_address_type" validate:"required,addressPoolNetTypeValidator"`

	// IP address
	// Required: true
	IPAddr string `url:"ip_addr" json:"ip_addr" validate:"required"`

	// End of IP address range
	// Required: false
	IPAddrRangeEnd string `url:"ip_addr_range_end,omitempty" json:"ip_addr_range_end,omitempty"`

	// IP prefix
	// Required: false
	IPPrefix string `url:"ip_prefix,omitempty" json:"ip_prefix,omitempty"`

	// MAC address
	// Required: false
	MACAddr string `url:"mac_addr,omitempty" json:"mac_addr,omitempty"`
}

// Update updates a address pool
func (i AddressPools) Update(ctx context.Context, req UpdateRequest) (*NetworkAddressPool, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return nil, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/sdn/address_pool/update"

	res, err := i.client.DecortApiCallCtype(ctx, http.MethodPut, url, constants.MIMEJSON, req)
	if err != nil {
		return nil, err
	}

	info := NetworkAddressPool{}

	err = json.Unmarshal(res, &info)
	if err != nil {
		return nil, err
	}

	return &info, nil
}
