package sep

import (
	"context"
	"net/http"
	"strconv"
	"strings"

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

// SharedLockStartRequest struct to start shared locks
type SharedLockStartRequest struct {
	// Storage endpoint provider ID
	// Required: true
	SEPID uint64 `url:"sep_id" json:"sep_id" validate:"required"`

	// List of node IDs for start locks
	// Required: false
	Nodes []uint64 `url:"nodes,omitempty" json:"nodes,omitempty"`

	// List of pool names for start locks
	// Required: false
	VGNames []string `url:"vg_names,omitempty" json:"vg_names,omitempty"`

	// If there are LOCKs, ignore them
	// Default: false
	// Required: false
	IgnoreStartedLock bool `url:"ignore_started_lock" json:"ignore_started_lock"`
}

type wrapperSharedLockStartRequest struct {
	SharedLockStartRequest

	AsyncMode bool `url:"sync"`
}

// SharedLockStart start shared locks without AsyncMode
func (s SEP) SharedLockStart(ctx context.Context, req SharedLockStartRequest) (bool, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return false, validators.ValidationErrors(validators.GetErrors(err))
	}

	reqWrapped := wrapperSharedLockStartRequest{
		SharedLockStartRequest: req,
		AsyncMode:              false,
	}

	url := "/cloudbroker/sep/sharedLockStart"

	res, err := s.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
	if err != nil {
		return false, err
	}

	result, err := strconv.ParseBool(string(res))
	if err != nil {
		return false, err
	}

	return result, nil
}

// SharedLockStartAsync start shared locks with AsyncMode
func (s SEP) SharedLockStartAsync(ctx context.Context, req SharedLockStartRequest) (string, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return "", validators.ValidationErrors(validators.GetErrors(err))
	}

	reqWrapped := wrapperSharedLockStartRequest{
		SharedLockStartRequest: req,
		AsyncMode:              true,
	}

	url := "/cloudbroker/sep/sharedLockStart"

	res, err := s.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
	if err != nil {
		return "", err
	}

	result := strings.ReplaceAll(string(res), "\"", "")

	return result, nil
}
