package vfpool

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

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

// CreateRequest struct to create vfpool device
type CreateRequest struct {
	// Name of device
	// Required: true
	Name string `url:"name" json:"name" validate:"required"`

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

	// Name of device
	// Required: false
	Config []Config `url:"-" json:"config,omitempty" validate:"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"`
}

// Config struct for CreateRequest
type Config struct {
	// Node ID
	// Required: true
	NodeID uint64 `url:"nodeId" json:"nodeId" validation:"required"`

	// NicName
	// Required: true
	NicName string `url:"nicName" json:"nicName" validation:"required"`

	// VF IDs
	// Required: true
	VFIDs []uint64 `url:"vfIds" json:"vfIds" validation:"required"`
}

type wrapperCreateRequest struct {
	CreateRequest
	Config []string `url:"config,omitempty"`
}

// Create creates vfpool device
func (v VFPool) Create(ctx context.Context, req CreateRequest) (uint64, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return 0, validators.ValidationErrors(validators.GetErrors(err))
	}

	var config []string

	if len(req.Config) != 0 {
		config = make([]string, 0, len(req.Config))

		for c := range req.Config {
			b, err := json.Marshal(req.Config[c])
			if err != nil {
				return 0, err
			}

			config = append(config, string(b))
		}
	} else {
		config = []string{}
	}

	reqWrapped := wrapperCreateRequest{
		CreateRequest: req,
		Config:        config,
	}

	url := "/cloudbroker/vfpool/create"

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

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

	return result, nil
}
