package compute

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

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

// ChangeIPRequest struct to change IP for network
type ChangeIPRequest struct {
	// ID of compute instance
	// Required: true
	ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`

	// Network type
	// 'EXTNET' for connect to external network directly
	// 'VINS' for connect to ViNS
	// Required: true
	NetType string `url:"net_type" json:"net_type" validate:"computeNetType"`

	// Network ID for connect to
	// For EXTNET - external network ID
	// For VINS - VINS ID
	// Required: true
	NetID uint64 `url:"net_id" json:"net_id" validate:"required"`

	// IP address to which we will change the existing one, it must be from the same subnet
	// Required: true
	IPAddr string `url:"ip_addr" json:"ip_addr" validate:"required"`
}

type wrapperChangeIPRequest struct {
	ChangeIPRequest

	AsyncMode bool `url:"asyncMode"`
}

// ChangeIP change reserved IP for compute instance
func (c Compute) ChangeIP(ctx context.Context, req ChangeIPRequest) (bool, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return false, validators.ValidationErrors(validators.GetErrors(err))
	}

	reqWrapped := wrapperChangeIPRequest{
		ChangeIPRequest: req,
		AsyncMode:       false,
	}

	url := "/cloudbroker/compute/changeIp"

	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
}

// ChangeIPAsync change reserved IP for compute instance with AsyncMode
func (c Compute) ChangeIPAsync(ctx context.Context, req ChangeIPRequest) (string, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return "", validators.ValidationErrors(validators.GetErrors(err))
	}

	reqWrapped := wrapperChangeIPRequest{
		ChangeIPRequest: req,
		AsyncMode:       true,
	}

	url := "/cloudbroker/compute/changeIp"

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

	return string(res), nil
}
