package vfpool

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

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

// UpdateRequest struct to update vfpool device
type UpdateRequest struct {
	// VFPool device ID
	// Required: true
	VFPoolID uint64 `url:"id" json:"id" validate:"required"`

	// Name of vfpool device
	// Required: false
	Name string `url:"name,omitempty" json:"name,omitempty"`

	// Description
	// Required: false
	Description string `url:"description,omitempty" json:"description,omitempty"`

	// Name of device
	// Required: false
	Config []Config `url:"-" json:"config,omitempty" validation:"omitempty,dive"`

	// List of Account IDs
	// Required: false
	AccountAccess []uint64 `url:"accountAccess,omitempty" json:"accountAccess,omitempty"`

	// List of RG IDs
	// Required: false
	RGAccess []uint64 `url:"rgAccess,omitempty" json:"rgAccess,omitempty"`
}

type wrapperUpdateRequest struct {
	UpdateRequest
	Config string `url:"config,omitempty"`
}

// Update updates vfpool device
func (v VFPool) Update(ctx context.Context, req UpdateRequest) (bool, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return false, validators.ValidationErrors(validators.GetErrors(err))
	}

	var config string

	if len(req.Config) != 0 {
		b, err := json.Marshal(req.Config)
		if err != nil {
			return false, err
		}

		config = string(b)
	}

	reqWrapped := wrapperUpdateRequest{
		UpdateRequest: req,
		Config:        config,
	}

	url := "/cloudbroker/vfpool/update"

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