package disks

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

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

// UpdateRequest struct to update disk
type UpdateRequest struct {
	// ID of the disk to update
	// Required: true
	DiskID uint64 `url:"disk_id" json:"disk_id" validate:"required"`

	// Cache mode of disk
	// Required: false
	Cache string `url:"cache,omitempty" json:"cache,omitempty"`

	// Discard
	// Required: false
	Discard string `url:"discard,omitempty" json:"discard,omitempty"`

	// Block size of disk
	// Required: false
	BlockSize string `url:"block_size,omitempty" json:"block_size,omitempty"`
}

type wrapperUpdateRequest struct {
	UpdateRequest

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

// Update updates disk
func (d Disks) Update(ctx context.Context, req UpdateRequest) (bool, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return false, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/disks/update"

	wrappedReq := wrapperUpdateRequest{
		UpdateRequest: 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
}

// UpdateAsync updates disk in async mode
func (d Disks) UpdateAsync(ctx context.Context, req UpdateRequest) (string, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return "", validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/disks/update"

	wrappedReq := wrapperUpdateRequest{
		UpdateRequest: 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
}
