/**
 * System-level hooks: diagnostics + active task snapshot.
 *
 * The vanilla UI polled /api/system/diagnostics and /api/system/tasks on
 * an interval. We replace the polling with TanStack Query's refetchInterval
 * — same effect, but participates in the shared cache and survives route
 * transitions without setting up its own setInterval bookkeeping.
 */

import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "./client";

export type DiagDoc = {
  id: string;
  title: string;
  status: string;
  case_number: string;
  created_at: string | null;
};

/** Halacha review backlog (GAP-14 / INV-QA1 / G10) — human-gate visibility. */
export type HalachaBacklog = {
  pending_review: number;
  pending_clean: number;
  pending_flagged: number;
  approved: number;
  rejected: number;
  deferred: number;
  published: number;
  total: number;
  reviewed_total: number;
  oldest_pending_at: string | null;
  throughput_24h: number;
  throughput_7d: number;
};

export type Diagnostics = {
  db_ok: boolean;
  tables: Record<string, number | null>;
  // ADM-1 (INV-IA5): the backend returns this human-gate counter; render it
  // rather than silently dropping it. /approvals owns the action (INV-IA1).
  halacha_backlog: HalachaBacklog;
  failed_documents: DiagDoc[];
  stuck_documents: DiagDoc[];
  active_tasks: Array<{
    task_id: string;
    filename: string;
    status: string;
    step: string;
  }>;
};

export function useDiagnostics() {
  return useQuery({
    queryKey: ["system", "diagnostics"] as const,
    queryFn: ({ signal }) =>
      apiRequest<Diagnostics>("/api/system/diagnostics", { signal }),
    refetchInterval: 10_000,
    staleTime: 5_000,
  });
}
