import { useQuery } from "@tanstack/react-query";
import { api } from "@/lib/api";
import type { ClaimAck } from "@/types";

/**
 * Per-claim acknowledgments query (ClaimDrawer · SP28 §5.1).
 *
 * Lists every `claim_acks` row for the given claim (per-claim only —
 * the backend filters out TA1 batch-level rows with
 * `claim_id IS NULL`). Drives the new `<Acknowledgments />` panel
 * inside `ClaimDrawer`.
 *
 * Returns `{ data, isLoading, isError, error, refetch }`:
 *  - `claimId === null` (drawer closed): the query is disabled and the
 *    hook short-circuits to `{ data: null, ... }` so a closed drawer
 *    doesn't burn a network request or a TanStack cache slot. The
 *    `ClaimDrawer` panel guards the `data ?? []` access on this.
 *  - `claimId` is set: fetches
 *    `GET /api/claims/{claim_id}/acks` via `api.listClaimAcks`.
 *    Cached 30 s — the link rows don't change once created (only
 *    manual-match / unlink mutate them, and those fire
 *    `claim_ack_written` / `claim_ack_dropped` events that the
 *    live-tail subscription delivers via `useTailStream("claim-acks")`).
 *  - On 404: the hook's retry predicate short-circuits (no retries)
 *    so the drawer's not-found state appears immediately rather than
 *    being masked by three back-to-back retry attempts.
 *
 * The live-tail subscription (`useTailStream("claim-acks")` +
 * `useMergedTail("claim-acks", data ?? [], (link) => link.claimId === claimId)`)
 * is mounted by the `ClaimDrawer` itself (per
 * `cyclone-frontend-page` convention #3 — subscription on the page,
 * not in the hook).
 */
export function useClaimAcks(claimId: string | null): {
  data: ClaimAck[] | null;
  isLoading: boolean;
  isError: boolean;
  error: Error | null;
  refetch: () => void;
} {
  const q = useQuery<ClaimAck[]>({
    queryKey: ["claim-acks", claimId],
    queryFn: () => api.listClaimAcks(claimId as string),
    enabled: claimId !== null,
    staleTime: 30 * 1000,
    retry: (failureCount, error) => {
      // Don't retry 404 — same posture as the other detail hooks. The
      // drawer treats 404 as a distinct "claim doesn't exist" state
      // and doesn't want retries masking it.
      if (error instanceof Error && "status" in error) {
        const status = (error as { status?: unknown }).status;
        if (status === 404) return false;
      }
      return failureCount < 3;
    },
  });

  if (claimId === null) {
    return {
      data: null,
      isLoading: false,
      isError: false,
      error: null,
      refetch: () => {},
    };
  }

  return {
    data: q.data ?? null,
    isLoading: q.isLoading,
    isError: q.isError,
    error: q.error,
    refetch: () => {
      void q.refetch();
    },
  };
}