package node

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

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

// ListRequest struct to get list of nodes
type ListRequest struct {
	// Find by node ID
	// Required: false
	ByID uint64 `url:"by_id,omitempty" json:"by_id,omitempty"`

	// Find by node name
	// Required: false
	Name string `url:"name,omitempty" json:"name,omitempty"`

	// Find by node version
	// Required: false
	Version string `url:"version,omitempty" json:"version,omitempty"`

	// Find by node release
	// Required: false
	Release string `url:"release,omitempty" json:"release,omitempty"`

	// Find by sep ID
	// Required: false
	SepID uint64 `url:"sepId,omitempty" json:"sepId,omitempty"`

	// Find by node roles
	// Required: false
	Role string `url:"role,omitempty" json:"role,omitempty"`

	// Find by node status
	// Required: false
	Status string `url:"status,omitempty" json:"status,omitempty"`

	// Sort by one of supported fields, format +|-(field)
	// Required: false
	SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`

	// Page number
	// Required: false
	Page uint64 `url:"page,omitempty" json:"page,omitempty"`

	// Page size
	// Required: false
	Size uint64 `url:"size,omitempty" json:"size,omitempty"`

	// Find by zone ID
	// Required: false
	ZoneID uint64 `url:"zone_id,omitempty" json:"zone_id,omitempty"`
}

// List gets list of all nodes as a ListNodes struct
func (n Node) List(ctx context.Context, req ListRequest) (*ListNodes, error) {

	res, err := n.ListRaw(ctx, req)
	if err != nil {
		return nil, err
	}

	list := ListNodes{}

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

	return &list, nil
}

// ListRaw gets list of all nodes as an array of bytes
func (n Node) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {

	err := validators.ValidateRequest(req)
	if err != nil {
		return nil, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/node/list"

	res, err := n.client.DecortApiCall(ctx, http.MethodPost, url, req)
	return res, err
}
