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

/**
 * React Query binding for the side-by-side batch diff.
 *
 * Query key: ``["batch-diff", a, b]`` so picking different batches
 * automatically produces a separate cache entry. ``enabled`` short-
 * circuits when either id is missing — the page disables the Run
 * button until both pickers are filled in, but we double-check here
 * so a half-picked URL can't fire an empty query.
 *
 * 404s from the backend are surfaced as ``ApiError(404)`` — the page
 * branches on ``error.status === 404`` to render the "one of these
 * batches was deleted out from under you" state instead of the
 * generic error toast. Matches the same convention used by the
 * claim detail drawer.
 */
export function useBatchDiff(a: string | null, b: string | null) {
  return useQuery<BatchDiff, ApiError>({
    queryKey: ["batch-diff", a, b],
    queryFn: () => api.getBatchDiff(a as string, b as string),
    enabled:
      api.isConfigured &&
      typeof a === "string" &&
      a.length > 0 &&
      typeof b === "string" &&
      b.length > 0,
    // Refetch on window focus would be nice in production; for the
    // diff view it's pointless because the underlying batches don't
    // change shape without a fresh ingest.
    refetchOnWindowFocus: false,
  });
}
