package compute

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

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

// RedeployRequest struct to redeploy
type RedeployRequest struct {
	// ID of compute instance
	// Required: true
	ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`

	// Storage policy id of compute. The rules of the specified storage policy will be used.
	// Required: false
	StoragePolicyID uint64 `url:"storage_policy_id,omitempty" json:"storage_policy_id,omitempty"`

	// ID of the new OS image, if image change is required
	// Required: false
	ImageID uint64 `url:"imageId,omitempty" json:"imageId,omitempty"`

	// The OS version that will be installed on the virtual machine
	// Required: false
	OSVersion string `url:"os_version,omitempty" json:"os_version,omitempty"`

	// new size for the boot disk in GB, if boot disk size change is required
	// Required: false
	DiskSize uint64 `url:"diskSize,omitempty" json:"diskSize,omitempty"`

	// How to handle data disks connected to this compute instance,
	// KEEP, DETACH, DESTROY
	// Required: false
	DataDisks string `url:"dataDisks,omitempty" json:"dataDisks,omitempty"`

	// Should compute be restarted upon successful redeploy
	// Required: false
	AutoStart bool `url:"autoStart,omitempty" json:"autoStart,omitempty"`

	// Set this flag to True to force stop running compute instance and redeploy next
	// Required: false
	ForceStop bool `url:"forceStop,omitempty" json:"forceStop,omitempty"`
}

type wrapperRedeployRequest struct {
	RedeployRequest

	AsyncMode bool `url:"asyncMode"`
}

// Redeploy redeploys compute
func (c Compute) Redeploy(ctx context.Context, req RedeployRequest) (bool, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return false, validators.ValidationErrors(validators.GetErrors(err))
	}

	reqWrapped := wrapperRedeployRequest{
		RedeployRequest: req,
		AsyncMode:       false,
	}

	url := "/cloudapi/compute/redeploy"

	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
}

// RedeployAsync redeploys compute with AsyncMode
func (c Compute) RedeployAsync(ctx context.Context, req RedeployRequest) (string, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return "", validators.ValidationErrors(validators.GetErrors(err))
	}

	reqWrapped := wrapperRedeployRequest{
		RedeployRequest: req,
		AsyncMode:       true,
	}

	url := "/cloudapi/compute/redeploy"

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

	return string(res), nil
}
