package trunk

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

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

// ListRequest struct to get list of trunks
type ListRequest struct {
	// Account access ID to filter by
	AccountIDs []uint64 `url:"account_ids,omitempty" json:"account_ids,omitempty"`

	// ID of the trunk to filter by
	IDs []uint64 `url:"ids,omitempty" json:"ids,omitempty"`

	// Sort by one of supported fields, format ±<field>
	SortBy string `url:"sort_by,omitempty" json:"sort_by,omitempty"`

	// Trunk tags to filter by
	TrunkTags string `url:"trunk_tags,omitempty" json:"trunk_tags,omitempty" validate:"omitempty,trunkTags"`

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

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

	// Status
	Status string `url:"status,omitempty" json:"status,omitempty"`
}

// List gets list of all trunks as a ListTrunks struct
func (t Trunk) List(ctx context.Context, req ListRequest) (*ListTrunks, error) {

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

	list := ListTrunks{}

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

	return &list, nil
}

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

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

	url := "/cloudapi/trunk/list"

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