package compute

import (
	"context"
	"net/http"
	"strconv"

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

// ChangeSecGroupsRequest struct to change security groups for compute
type ChangeSecGroupsRequest struct {
	// Identifier compute
	// Required: true
	ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`

	// Interface name or MAC address
	// Required: true
	Interface string `url:"interface" json:"interface" validate:"required"`

	// List of security group IDs to assign to this interface
	// Required: false
	SecGroups []uint64 `url:"security_groups,omitempty" json:"security_groups,omitempty"`

	// Flag indicating whether security groups are enabled for this interface
	// Required: false
	EnableSecGroups interface{} `url:"enable_secgroups,omitempty" json:"enable_secgroups,omitempty" validate:"omitempty,isBool"`
}

type wrapperChangeSecGroupsRequest struct {
	ChangeSecGroupsRequest

	AsyncMode bool `url:"asyncMode"`
}

// ChangeSecGroups changes security groups for compute
func (c Compute) ChangeSecGroups(ctx context.Context, req ChangeSecGroupsRequest) (bool, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return false, validators.ValidationErrors(validators.GetErrors(err))
	}

	reqWrapped := wrapperChangeSecGroupsRequest{
		ChangeSecGroupsRequest: req,
		AsyncMode:              false,
	}

	url := "/cloudbroker/compute/change_security_groups"

	res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
	if err != nil {
		return false, err
	}

	result, err := strconv.ParseBool(string(res))
	if err != nil {
		return false, err
	}

	return result, nil
}

// ChangeSecGroupsAsync changes security groups for compute with AsyncMode
func (c Compute) ChangeSecGroupsAsync(ctx context.Context, req ChangeSecGroupsRequest) (string, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return "", validators.ValidationErrors(validators.GetErrors(err))
	}

	reqWrapped := wrapperChangeSecGroupsRequest{
		ChangeSecGroupsRequest: req,
		AsyncMode:              true,
	}

	url := "/cloudbroker/compute/change_security_groups"

	res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
	if err != nil {
		return "", err
	}

	return string(res), nil
}
