package disks

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

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

// MigrateAbortRequest struct to abort migration
type MigrateAbortRequest struct {
	// ID of the disk
	// Required: true
	DiskID uint64 `url:"disk_id" json:"disk_id" validate:"required"`
}

type wrapperMigrateAbortRequest struct {
	MigrateAbortRequest

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

// MigrateAbort aborts disk migration
func (c Disks) MigrateAbort(ctx context.Context, req MigrateAbortRequest) (bool, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return false, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/disks/migrate_abort"

	wrappedReq := wrapperMigrateAbortRequest{
		MigrateAbortRequest: req,
		AsyncMode:           false,
	}

	res, err := c.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
}

// MigrateAbortAsync aborts disk migration in async mode
func (c Disks) MigrateAbortAsync(ctx context.Context, req MigrateAbortRequest) (string, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return "", validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/disks/migrate_abort"

	wrappedReq := wrapperMigrateAbortRequest{
		MigrateAbortRequest: req,
		AsyncMode:           true,
	}

	res, err := c.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
}
