package stpolicy

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

	"repository.basistech.ru/BASIS/dynamix-golang-sdk/v14/internal/constants"
	"repository.basistech.ru/BASIS/dynamix-golang-sdk/v14/internal/validators"
)

type UpdateRequest struct {
	// ID of storage policy
	// Required: true
	StoragePolicyID uint64 `url:"storage_policy_id" json:"storage_policy_id" validate:"required"`

	// List of storage endpoint access objects
	// Required: false
	AccessSEPsPools []AccessSEPsPool `url:"access_seps_pools,omitempty" json:"access_seps_pools,omitempty"`

	// New name for the storage policy
	// Required: false
	Name string `url:"name,omitempty" json:"name,omitempty"`

	// New value for limit IOPS
	// Required: false
	LimitIOPS uint64 `url:"limit_iops,omitempty" json:"limit_iops,omitempty"`

	// New description of the storage policy
	// Required: false
	Description string `url:"description,omitempty" json:"description,omitempty"`
}

// Update updates storage policy
func (sp StPolicy) Update(ctx context.Context, req UpdateRequest) (*InfoStoragePolicyWithID, error) {
	res, err := sp.UpdateRaw(ctx, req)
	if err != nil {
		return nil, err
	}

	info := InfoStoragePolicyWithID{}

	err = json.Unmarshal(res, &info)
	if err != nil {
		return nil, err
	}

	return &info, nil
}

func (sp StPolicy) UpdateRaw(ctx context.Context, req UpdateRequest) ([]byte, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return nil, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/storage_policy/update"

	res, err := sp.client.DecortApiCallCtype(ctx, http.MethodPost, url, constants.MIMEJSON, req)
	return res, err
}
