package disks

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

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

// ChangeDiskStoragePolicyRequest struct to change storage policy for disk
type ChangeDiskStoragePolicyRequest struct {
	// ID of the disk
	// Required: true
	DiskID uint64 `url:"disk_id" json:"disk_id" validate:"required"`

	// ID of the storage policy to which to connect account
	// Required: true
	StoragePolicyID uint64 `url:"storage_policy_id" json:"storage_policy_id" validate:"required"`
}

type wrapperChangeDiskStoragePolicyRequest struct {
	ChangeDiskStoragePolicyRequest

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

// ChangeDiskStoragePolicy changes storage policy for disk
func (d Disks) ChangeDiskStoragePolicy(ctx context.Context, req ChangeDiskStoragePolicyRequest) (bool, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return false, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/disks/change_disk_storage_policy"

	wrappedReq := wrapperChangeDiskStoragePolicyRequest{
		ChangeDiskStoragePolicyRequest: 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
}

// ChangeDiskStoragePolicyAsync changes storage policy for disk in async mode
func (d Disks) ChangeDiskStoragePolicyAsync(ctx context.Context, req ChangeDiskStoragePolicyRequest) (string, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return "", validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/disks/change_disk_storage_policy"

	wrappedReq := wrapperChangeDiskStoragePolicyRequest{
		ChangeDiskStoragePolicyRequest: 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
}
