package disks

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

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

// SnapshotRollbackRequest struct to rollback snapshot
type SnapshotRollbackRequest struct {
	// ID of the disk
	// Required: true
	DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`

	// Label of the snapshot to rollback
	// Required: false
	Label string `url:"label,omitempty" json:"label,omitempty"`

	// Timestamp of the snapshot to rollback
	// Required: false
	TimeStamp uint64 `url:"timestamp,omitempty" json:"timestamp,omitempty"`
}

type wrapperSnapshotRollbackRequest struct {
	SnapshotRollbackRequest

	AsyncMode bool `url:"async_mode" json:"async_mode"`
}

// SnapshotRollback rollbacks an individual disk snapshot
func (d Disks) SnapshotRollback(ctx context.Context, req SnapshotRollbackRequest) (bool, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return false, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/disks/snapshotRollback"

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

	res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, wrappedReq)
	if err != nil {
		return false, err
	}

	result, err := strconv.ParseBool(string(res))
	if err != nil {
		return false, err
	}

	return result, nil
}

// SnapshotRollbackAsync rollbacks an individual disk snapshot in async mode
func (d Disks) SnapshotRollbackAsync(ctx context.Context, req SnapshotRollbackRequest) (string, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return "", validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/disks/snapshotRollback"

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

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

	var result string
	if err := json.Unmarshal(res, &result); err != nil {
		return "", err
	}

	return result, nil
}
