package policies

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

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

// ListRequest struct to get a list of policies
type ListRequest struct {
	// Router ID
	// Required: true
	RouterID string `url:"router_id" json:"router_id" validate:"required"`

	// Filter by display name
	// Required: false
	DisplayName string `url:"display_name,omitempty" json:"display_name,omitempty"`

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

	// Number of results per page
	// Required: false
	PerPage uint64 `url:"per_page,omitempty" json:"per_page,omitempty"`

	// Field to sort by (display_name, subnet, created_at, updated_at)
	// Required: false
	SortBy string `url:"sort_by,omitempty" json:"sort_by,omitempty" validate:"omitempty,oneof=display_name subnet created_at updated_at"`

	// Sort order (asc/desc)
	// Required: false
	SortOrder string `url:"sort_order,omitempty" json:"sort_order,omitempty" validate:"omitempty,oneof=asc desc"`
}

// List of policies
func (i Policies) List(ctx context.Context, req ListRequest) (PoliciesList, error) {
	res, err := i.ListRaw(ctx, req)
	if err != nil {
		return nil, err
	}

	pools := []Policy{}

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

	return pools, nil
}

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

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

	url := "/sdn/router/policies/list"

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