import { useQuery } from '@tanstack/react-query';
import { bookingsApi } from '../apis';
import { bookingKeys } from '../keys';
import { BOOKING_DETAIL_STALE_TIME } from '../constants';
import type { BookingSessionDto, BookingViewerRole } from '../types';

/**
 * The session schedule for a booking. Sessions are **embedded** in the booking detail (the contract
 * exposes no standalone per-booking session-list endpoint), so this shares the `bookingDetail(id)` query
 * key + queryFn and `select`s `sessions` — it dedupes with `useBookingDetail` and never fires a second
 * request. Invalidating `bookingDetail(id)` (which the EVV mutations do) refreshes it automatically.
 */
export function useBookingSessions(id: number | undefined, viewerRole: BookingViewerRole) {
  return useQuery({
    queryKey: bookingKeys.bookingDetail(id ?? -1),
    queryFn: () => bookingsApi.getBookingDetail(id as number, viewerRole),
    enabled: id != null && id > 0,
    staleTime: BOOKING_DETAIL_STALE_TIME,
    select: (detail): BookingSessionDto[] => detail.sessions,
  });
}
