import { useQuery } from '@tanstack/react-query';
import { ApiError } from '@/lib/api/errors';
import { paymentApi } from '../apis';
import { paymentKeys } from '../keys';
import { INVOICE_STALE_TIME } from '../constants';

/**
 * The booking's commission invoice (b11). An issued invoice is immutable — long `staleTime`, no polling.
 * A 404 is a domain state, not a transient failure ("not issued yet" — b11 issues via an admin action;
 * auto-issue on capture is filed as REQ-018), so it renders as an empty state and is **not retried**.
 */
export function useInvoice(bookingId: number | undefined) {
  return useQuery({
    queryKey: paymentKeys.invoice(bookingId ?? -1),
    queryFn: () => paymentApi.getInvoice(bookingId as number),
    enabled: bookingId != null && bookingId > 0,
    staleTime: INVOICE_STALE_TIME,
    retry: (failureCount, error) => {
      if (error instanceof ApiError && error.status === 404) return false;
      return failureCount < 3;
    },
  });
}
