import { useQuery } from '@tanstack/react-query';
import { bookingRequestsApi } from '../apis';
import { bookingRequestKeys } from '../keys';
import { BOOKING_REQUEST_GC_TIME, BOOKING_REQUEST_POLL_MS, BOOKING_REQUEST_STALE_TIME } from '../constants';
import { isTerminalBookingRequestStatus, type RequestRole } from '../types';

/**
 * A single booking request (C5 customer view + the nurse request detail). **Polls** while the status is
 * non-terminal so an accept / reject / expire transition surfaces without a manual refresh, and **stops**
 * polling once a terminal/`converted` status is reached. `role` drives the mock's nurse-view masking (the
 * real server infers it from auth). Enabled only when an id is present.
 */
export function useBookingRequest(id: number | undefined, role: RequestRole) {
  return useQuery({
    queryKey: bookingRequestKeys.detail(id ?? -1),
    queryFn: () => bookingRequestsApi.get(id as number, role),
    enabled: id != null && id > 0,
    staleTime: BOOKING_REQUEST_STALE_TIME,
    gcTime: BOOKING_REQUEST_GC_TIME,
    refetchInterval: (query) => {
      const status = query.state.data?.status;
      return status && isTerminalBookingRequestStatus(status) ? false : BOOKING_REQUEST_POLL_MS;
    },
  });
}
