package ai.sentryagent.idp.services;

import ai.sentryagent.idp.internal.HttpHelper;
import ai.sentryagent.idp.models.AuditEvent;
import ai.sentryagent.idp.models.PaginatedAuditEvents;
import ai.sentryagent.idp.models.QueryAuditParams;

import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;

/**
 * Client for the Audit Log API endpoints.
 * Provides both synchronous and asynchronous (CompletableFuture) methods.
 */
public final class AuditClient {

    private final String baseUrl;
    private final Supplier<String> tokenSupplier;
    private final HttpHelper http;

    public AuditClient(String baseUrl, Supplier<String> tokenSupplier, HttpHelper http) {
        this.baseUrl       = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
        this.tokenSupplier = tokenSupplier;
        this.http          = http;
    }

    // ─── Sync ─────────────────────────────────────────────────────────────────

    /** GET /api/v1/audit → 200 PaginatedAuditEvents */
    public PaginatedAuditEvents queryAuditLog(QueryAuditParams params) {
        return http.request("GET", buildQueryUrl(params), null, tokenSupplier.get(), PaginatedAuditEvents.class);
    }

    /** GET /api/v1/audit/:id → 200 AuditEvent */
    public AuditEvent getAuditEvent(String eventId) {
        return http.request("GET", baseUrl + "/api/v1/audit/" + eventId, null, tokenSupplier.get(), AuditEvent.class);
    }

    // ─── Async ────────────────────────────────────────────────────────────────

    /** Async version of {@link #queryAuditLog}. */
    public CompletableFuture<PaginatedAuditEvents> queryAuditLogAsync(QueryAuditParams params) {
        return CompletableFuture.supplyAsync(tokenSupplier)
            .thenCompose(token -> http.requestAsync("GET", buildQueryUrl(params), null, token, PaginatedAuditEvents.class));
    }

    /** Async version of {@link #getAuditEvent}. */
    public CompletableFuture<AuditEvent> getAuditEventAsync(String eventId) {
        return CompletableFuture.supplyAsync(tokenSupplier)
            .thenCompose(token -> http.requestAsync("GET", baseUrl + "/api/v1/audit/" + eventId, null, token, AuditEvent.class));
    }

    // ─── URL builder ──────────────────────────────────────────────────────────

    private String buildQueryUrl(QueryAuditParams params) {
        StringBuilder url   = new StringBuilder(baseUrl + "/api/v1/audit");
        StringBuilder query = new StringBuilder();
        if (params != null) {
            appendParam(query, "agentId",   params.getAgentId());
            appendParam(query, "action",    params.getAction());
            appendParam(query, "outcome",   params.getOutcome());
            appendParam(query, "fromDate",  params.getFromDate());
            appendParam(query, "toDate",    params.getToDate());
            if (params.getPage()  != null) appendParam(query, "page",  params.getPage().toString());
            if (params.getLimit() != null) appendParam(query, "limit", params.getLimit().toString());
        }
        if (query.length() > 0) url.append("?").append(query.substring(1));
        return url.toString();
    }

    private static void appendParam(StringBuilder sb, String key, String value) {
        if (value != null && !value.isEmpty()) {
            sb.append("&").append(key).append("=").append(value);
        }
    }
}
