package session

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

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

type ListRequest struct {
	// Filter by username
	User string `url:"user,omitempty" json:"user,omitempty"`

	// Filter by authorization system (bvs, decs3o, password)
	AuthorizeSystem string `url:"authorize_system,omitempty" json:"authorize_system,omitempty"`

	// Filter by public session ID (UUID)
	PublicSessionID string `url:"public_session_id,omitempty" json:"public_session_id,omitempty"`

	// Filter by sub from JWT
	Sub string `url:"sub,omitempty" json:"sub,omitempty"`

	// Filter by sid from JWT
	SID uint64 `url:"sid,omitempty" json:"sid,omitempty"`

	// Filter sessions with login_time >= timestamp (Unix timestamp)
	TimestampAt uint64 `url:"timestamp_at,omitempty" json:"timestamp_at,omitempty"`

	// Filter sessions with login_time <= timestamp (Unix timestamp)
	TimestampTo uint64 `url:"timestamp_to,omitempty" json:"timestamp_to,omitempty"`

	// Filter sessions active at this timestamp (login_time <= T < logout_time/expires_at)
	ActiveAt uint64 `url:"active_at,omitempty" json:"active_at,omitempty"`

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

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

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

// List gets list of sessions as a ListSession struct
func (s Session) List(ctx context.Context, req ListRequest) (*ListSession, error) {

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

	list := ListSession{}

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

	return &list, nil
}

// ListRaw gets list of sessions as an array of bytes
func (s Session) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {

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

	url := "/cloudbroker/session/list"

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