package compute

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

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

// SnapshotRollbackRequest struct for rollback
type SnapshotRollbackRequest struct {
	// ID of the compute instance
	// Required: true
	ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`

	// Text label of snapshot to rollback
	// Required: true
	Label string `url:"label" json:"label" validate:"required"`

	// Rollback with memory dump restore
	// Required: false
	// Default: true
	WithMemory interface{} `url:"with_memory,omitempty" json:"with_memory,omitempty" validate:"omitempty,isBool"`
}

type wrapperSnapshotRollbackRequest struct {
	SnapshotRollbackRequest
	AsyncMode bool `url:"asyncMode"`
}

// SnapshotRollback rollbacks specified compute snapshot
func (c Compute) SnapshotRollback(ctx context.Context, req SnapshotRollbackRequest) (bool, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return false, validators.ValidationErrors(validators.GetErrors(err))
	}

	reqWrapped := wrapperSnapshotRollbackRequest{
		SnapshotRollbackRequest: req,
		AsyncMode:               false,
	}

	url := "/cloudapi/compute/snapshotRollback"

	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
}

// SnapshotRollbackAsync rollbacks specified compute snapshot in async mode
func (c Compute) SnapshotRollbackAsync(ctx context.Context, req SnapshotRollbackRequest) (string, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return "", validators.ValidationErrors(validators.GetErrors(err))
	}

	reqWrapped := wrapperSnapshotRollbackRequest{
		SnapshotRollbackRequest: req,
		AsyncMode:               true,
	}

	url := "/cloudapi/compute/snapshotRollback"

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

	return string(res), nil
}
