package secgroup

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

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

type ListRequest struct {
	// Search by security group id
	// Required: false
	ByID uint64 `url:"by_id,omitempty" json:"by_id,omitempty"`

	// Search by account id
	// Required: false
	AccountID uint64 `url:"account_id,omitempty" json:"account_id,omitempty"`

	// Search by security group name
	// Required: false
	Name string `url:"name,omitempty" json:"name,omitempty"`

	// Search by security group description
	// Required: false
	Description string `url:"description,omitempty" json:"description,omitempty"`

	// Search by created after time (unix timestamp)
	// Required: false
	CreatedMin uint64 `url:"created_min,omitempty" json:"created_min,omitempty"`

	// Search by created before time (unix timestamp)
	// Required: false
	CreatedMax uint64 `url:"created_max,omitempty" json:"created_max,omitempty"`

	// Search by updated after time (unix timestamp)
	// Required: false
	UpdatedMin uint64 `url:"updated_min,omitempty" json:"updated_min,omitempty"`

	// Search by updated before time (unix timestamp)
	// Required: false
	UpdatedMax uint64 `url:"updated_max,omitempty" json:"updated_max,omitempty"`

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

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

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

// List gets list of security groups as a ListSecurityGroups struct
func (sg SecurityGroup) List(ctx context.Context, req ListRequest) (*ListSecurityGroups, error) {

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

	list := ListSecurityGroups{}

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

	return &list, nil
}

// ListRaw gets list of security groups as an array of bytes
func (sg SecurityGroup) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {

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

	url := "/cloudapi/security_group/list"

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