import { useQuery } from '@tanstack/react-query';
import { ticketsApi } from '../apis';
import { ticketKeys } from '../keys';
import { TICKETS_GC_TIME, TICKET_THREAD_STALE_TIME } from '../constants';
import type { TicketMessage } from '../types';
import { useTicketViewer } from './useTicketViewer';

/**
 * Just the messages of a thread — a `select` over the same `detail(id)` cache the header reads (mirrors the
 * f8 `useBookingSessions = select over detail`). One network fetch feeds both; the message list re-renders on
 * a new message without re-rendering the thread header. Optimistic sends mutate `detail(id)`, so the list
 * updates instantly.
 */
export function useTicketThread(ticketId: number | undefined) {
  const { userId } = useTicketViewer();
  return useQuery({
    queryKey: ticketKeys.detail(ticketId ?? -1),
    queryFn: () => ticketsApi.getTicket(ticketId as number, userId),
    enabled: ticketId != null && ticketId > 0,
    staleTime: TICKET_THREAD_STALE_TIME,
    gcTime: TICKETS_GC_TIME,
    select: (detail): TicketMessage[] => detail.messages,
  });
}
