package locations

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

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

// ListGetRequest struct to get list of locations
type ListGetRequest struct {
	// 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 flag
	// Required: false
	Flag string `url:"flag,omitempty" json:"flag,omitempty"`

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

	// Find by ID
	// Required: false
	ByID uint64 `url:"by_id,omitempty" json:"by_id,omitempty"`

	// Find by code location
	// Required: false
	LocationCode string `url:"locationCode,omitempty" json:"locationCode,omitempty"`

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

// ListGet gets list of all locations as a ListLocations struct
func (l Locations) ListGet(ctx context.Context, req ListGetRequest) (*ListLocations, error) {

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

	list := ListLocations{}

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

	return &list, nil
}

// ListGetRaw gets list of all locations as an array of bytes
func (l Locations) ListGetRaw(ctx context.Context, req ListGetRequest) ([]byte, error) {

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

	url := "/cloudapi/locations/list"

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