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

	// Node ID to pin to
	// Required: false
	TargetNodeID uint64 `url:"targetNodeId" json:"targetNodeId"`

	// Try to migrate or not if compute in running states
	// Required: false
	Force bool `url:"force" json:"force"`

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

type wrapperPinToNodeRequest struct {
	PinToNodeRequest

	AsyncMode bool `url:"asyncMode"`
}

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

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

	url := "/cloudbroker/compute/pin_to_node"

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

	result, err := strconv.ParseUint(string(res), 10, 64)
	if err != nil {
		return 0, 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 := "/cloudbroker/compute/pin_to_node"

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

	return string(res), nil
}
