package agentidp

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"strings"
)

// AuditClient provides methods for querying the Audit Log API endpoints.
type AuditClient struct {
	baseURL    string
	getToken   func(ctx context.Context) (string, error)
	httpClient *http.Client
}

func newAuditClient(baseURL string, getToken func(ctx context.Context) (string, error), httpClient *http.Client) *AuditClient {
	return &AuditClient{
		baseURL:    strings.TrimRight(baseURL, "/"),
		getToken:   getToken,
		httpClient: httpClient,
	}
}

// QueryAuditLog returns a filtered, paginated list of audit events.
// GET /api/v1/audit → 200 PaginatedAuditEvents
func (c *AuditClient) QueryAuditLog(ctx context.Context, params *QueryAuditParams) (*PaginatedAuditEvents, error) {
	token, err := c.getToken(ctx)
	if err != nil {
		return nil, err
	}
	rawURL := c.baseURL + "/api/v1/audit"
	if params != nil {
		q := url.Values{}
		if params.AgentID != "" {
			q.Set("agentId", params.AgentID)
		}
		if params.Action != "" {
			q.Set("action", params.Action)
		}
		if params.Outcome != "" {
			q.Set("outcome", params.Outcome)
		}
		if params.FromDate != "" {
			q.Set("fromDate", params.FromDate)
		}
		if params.ToDate != "" {
			q.Set("toDate", params.ToDate)
		}
		if params.Page > 0 {
			q.Set("page", fmt.Sprintf("%d", params.Page))
		}
		if params.Limit > 0 {
			q.Set("limit", fmt.Sprintf("%d", params.Limit))
		}
		if len(q) > 0 {
			rawURL += "?" + q.Encode()
		}
	}
	var result PaginatedAuditEvents
	if err := doRequest(ctx, c.httpClient, http.MethodGet, rawURL, nil, token, &result); err != nil {
		return nil, err
	}
	return &result, nil
}

// GetAuditEvent retrieves a single audit event by ID.
// GET /api/v1/audit/:id → 200 AuditEvent
func (c *AuditClient) GetAuditEvent(ctx context.Context, eventID string) (*AuditEvent, error) {
	token, err := c.getToken(ctx)
	if err != nil {
		return nil, err
	}
	var event AuditEvent
	if err := doRequest(ctx, c.httpClient, http.MethodGet, c.baseURL+"/api/v1/audit/"+eventID, nil, token, &event); err != nil {
		return nil, err
	}
	return &event, nil
}
