package segments

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 for updating segment
type UpdateRequest struct {
	// ID of segment
	// Required: true
	SegmentID string `url:"segment_id" json:"segment_id" validate:"required"`

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

	// Identifier of the parent access group
	// Required: true
	AccessGroupID string `url:"access_group_id" json:"access_group_id" validate:"required"`

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

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

	// 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"`

	// DHCP IPv4
	// Required: false
	DHCPv4 *DHCPv4ConfigRequest `url:"-" json:"dhcp_v4,omitempty"`

	// DHCP IPv6
	// Required: false
	DHCPv6 *DHCPv6ConfigRequest `url:"-" json:"dhcp_v6,omitempty"`

	// Segment type
	// Required: false
	Type string `url:"type,omitempty" json:"type,omitempty"`
}

// Update updates segment
func (s Segments) Update(ctx context.Context, req UpdateRequest) (*SegmentResponse, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return nil, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/sdn/segment/update"

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

	info := SegmentResponse{}

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

	return &info, nil
}
