package disks

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

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

// UnshareRequest struct to unshare data disk
type UnshareRequest struct {
	// ID of the disk to unshare
	// Required: true
	DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
}

type wrapperUnshareRequest struct {
	UnshareRequest

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

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

	url := "/cloudbroker/disks/unshare"

	wrappedReq := wrapperUnshareRequest{
		UnshareRequest: 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
}

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

	url := "/cloudbroker/disks/unshare"

	wrappedReq := wrapperUnshareRequest{
		UnshareRequest: 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
}
