package compute

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

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

// PinToNodeRequest struct to pin compute to node
type PinToNodeRequest struct {
	// ID of the compute instance
	// Required: true
	ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`

	// Auto start when node restarted
	// Required: false
	// Default: false
	AutoStart bool `url:"autoStart" json:"autoStart"`
}

type wrapperPinToNodeRequest struct {
	PinToNodeRequest

	AsyncMode bool `url:"asyncMode"`
}

// PinToNode pin compute to current node
func (c Compute) PinToNode(ctx context.Context, req PinToNodeRequest) (bool, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return false, validators.ValidationErrors(validators.GetErrors(err))
	}

	reqWrapped := wrapperPinToNodeRequest{
		PinToNodeRequest: req,
		AsyncMode:        false,
	}

	url := "/cloudapi/compute/pin_to_node"

	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
}

// PinToNodeAsync pins compute to current node with AsyncMode
func (c Compute) PinToNodeAsync(ctx context.Context, req PinToNodeRequest) (string, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return "", validators.ValidationErrors(validators.GetErrors(err))
	}

	reqWrapped := wrapperPinToNodeRequest{
		PinToNodeRequest: req,
		AsyncMode:        true,
	}

	url := "/cloudapi/compute/pin_to_node"

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

	return string(res), nil
}
