package rule

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

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

// ListRequest struct to get a list of security rules
type ListRequest struct {
	// Security policy ID
	// Required: true
	SecurityPolicyID string `url:"security_policy_id" json:"security_policy_id" validate:"required"`

	// Display name
	// Required: false
	DisplayName string `url:"display_name,omitempty" json:"display_name,omitempty"`

	// Enabled status
	// Required: false
	Enabled interface{} `url:"enabled,omitempty" json:"enabled,omitempty" validate:"omitempty,isBool"`

	// 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, enabled, created_at, updated_at, deleted_at, start_priority)
	// Required: false
	SortBy string `url:"sort_by,omitempty" json:"sort_by,omitempty"`

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

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

	result := []SecurityRule{}

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

	return result, nil
}

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

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

	url := "/sdn/security_policy/rule/list"

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