import { useQuery } from "@tanstack/react-query";
import { apiFetch } from "./client";
import type { AuditResult } from "@/types/api";

export interface AuditQueryParams {
  provider?: string;
  min_sensitivity?: string;
  start?: string;
  end?: string;
  limit?: number;
  offset?: number;
}

function buildQueryString(params: Record<string, string | number | undefined>): string {
  const q = new URLSearchParams();
  for (const [k, v] of Object.entries(params)) {
    if (v !== undefined && v !== "") q.set(k, String(v));
  }
  const s = q.toString();
  return s ? `?${s}` : "";
}

export function useAuditLogs(params: AuditQueryParams = {}, refetchInterval?: number) {
  const qs = buildQueryString(params as Record<string, string | number | undefined>);
  return useQuery({
    queryKey: ["logs", params],
    queryFn: () => apiFetch<AuditResult>(`/v1/admin/logs${qs}`),
    refetchInterval,
  });
}

// Convenience hook for total request count
export function useRequestCount() {
  return useQuery({
    queryKey: ["logs", "count"],
    queryFn: () => apiFetch<AuditResult>("/v1/admin/logs?limit=1&offset=0"),
    select: (d) => d.total,
    refetchInterval: 30_000,
  });
}
