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

/**
 * Per-ack claims query (AckDrawer · SP28 §5.2).
 *
 * Lists every `claim_acks` row for the given ack. For 999/277CA,
 * one entry per AK2 / ClaimStatus (D1 per-AK2 granularity). For
 * TA1, one entry per envelope linked to the originating `Batch`.
 * Drives the new `<MatchedClaim />` panel inside `AckDrawer`.
 *
 * Returns `{ data, isLoading, isError, error, refetch }`:
 *  - `ackId === null` (drawer closed): the query is disabled and the
 *    hook short-circuits to the empty drawer state `{ data: null, ... }`
 *    so a closed drawer doesn't burn a network request or a TanStack
 *    cache slot. The `AckDrawer` panel guards the `data ?? []` access
 *    on this and renders the "Link to claim…" dropdown when the list
 *    is empty.
 *  - `kind` and `ackId` set: fetches
 *    `GET /api/acks/{kind}/{ack_id}/claims` via `api.listAckClaims`.
 *    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.ackId === ackId)`)
 * is mounted by the `AckDrawer` itself (per
 * `cyclone-frontend-page` convention #3 — subscription on the page,
 * not in the hook).
 */
export function useAckClaims(
  kind: ClaimAckKind | null,
  ackId: number | null,
): {
  data: ClaimAck[] | null;
  isLoading: boolean;
  isError: boolean;
  error: Error | null;
  refetch: () => void;
} {
  const q = useQuery<ClaimAck[]>({
    queryKey: ["ack-claims", kind, ackId],
    queryFn: () => api.listAckClaims(kind as ClaimAckKind, ackId as number),
    enabled: kind !== null && ackId !== null,
    staleTime: 30 * 1000,
    retry: (failureCount, error) => {
      // Don't retry 404 — same posture as the other detail hooks.
      if (error instanceof Error && "status" in error) {
        const status = (error as { status?: unknown }).status;
        if (status === 404) return false;
      }
      return failureCount < 3;
    },
  });

  if (kind === null || ackId === 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();
    },
  };
}