package disks

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

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

// ReplicateRequest struct to create an empty disk in chosen SEP and pool combination.
type ReplicateRequest struct {
	// Id of the disk to replicate. This disk will become master in replication
	// Required: true
	DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`

	// Name of replica disk to create
	// Required: true
	Name string `url:"name" json:"name" validate:"required"`

	// ID of SEP to create slave disk
	// Required: true
	SepID uint64 `url:"sepId" json:"sepId" validate:"required"`

	// Pool name to create slave disk in
	// Required: true
	PoolName string `url:"poolName" json:"poolName" validate:"required"`

	// ID of the storage policy under the disk will be created
	// Required: true
	StoragePolicyID uint64 `url:"storage_policy_id" json:"storage_policy_id" validate:"required"`
}

type wrapperReplicateRequest struct {
	ReplicateRequest

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

// Replicate create an empty disk in chosen SEP and pool combination.
// Starts replication between chosen disk and newly created disk
// Note: only TATLIN type SEP are supported for replications between
func (d Disks) Replicate(ctx context.Context, req ReplicateRequest) (uint64, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return 0, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudapi/disks/replicate"

	wrappedReq := wrapperReplicateRequest{
		ReplicateRequest: req,
		AsyncMode:        false,
	}

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

	result, err := strconv.ParseUint(string(res), 10, 64)
	if err != nil {
		return 0, err
	}

	return result, nil
}

// ReplicateAsync creates an empty disk in chosen SEP and pool combination in async mode.
// Starts replication between chosen disk and newly created disk
// Note: only TATLIN type SEP are supported for replications between
func (d Disks) ReplicateAsync(ctx context.Context, req ReplicateRequest) (string, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return "", validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudapi/disks/replicate"

	wrappedReq := wrapperReplicateRequest{
		ReplicateRequest: 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
}
