package extnet

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

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

// UpdateRequest struct for update extnet
type UpdateRequest struct {
	// ID of external network
	// Required: true
	ExtNetID string `url:"external_network_id" json:"external_network_id" validate:"required"`

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

	// Bridge network name
	// Required: true
	BridgeNetworkName string `url:"bridge_network_name" json:"bridge_network_name" validate:"required"`

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

	// User-friendly name for the external network
	// Required: true
	DisplayName string `url:"display_name" json:"display_name" validate:"required"`

	// List of hypervisor names
	// Required: true
	Hypervisors []string `url:"hypervisors" json:"hypervisors" validate:"required"`

	// Access group ID
	// Required: false
	AccessGroupID string `url:"access_group_id,omitempty" json:"access_group_id,omitempty"`

	// IPv4 default gateway address
	// Required: false
	DefaultGatewayIPv4 string `url:"default_gateway_ipv4,omitempty" json:"default_gateway_ipv4,omitempty"`

	// IPv6 default gateway address
	// Required: false
	DefaultGatewayIPv6 string `url:"default_gateway_ipv6,omitempty" json:"default_gateway_ipv6,omitempty"`

	// Whether the network is enabled
	// Required: true
	Enabled bool `url:"enabled" json:"enabled"`

	// IPv4 subnet in CIDR notation (Either subnet_v4 or subnet_v6 must be specified)
	// Required: false
	SubnetV4 string `url:"subnet_v4,omitempty" json:"subnet_v4,omitempty"`

	// IPv6 subnet in CIDR notation (Either subnet_v4 or subnet_v6 must be specified)
	// Required: false
	SubnetV6 string `url:"subnet_v6,omitempty" json:"subnet_v6,omitempty"`

	// VLAN tag identifier
	// Required: false
	VLANTag string `url:"vlan_tag,omitempty" json:"vlan_tag,omitempty" validate:"omitempty,trunkTags"`
}

// Update updated an external network
func (e ExtNet) Update(ctx context.Context, req UpdateRequest) (*ExternalNetworkResponse, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return nil, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/sdn/external_network/update"

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

	info := ExternalNetworkResponse{}

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

	return &info, nil
}
