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 { useTicketViewer } from './useTicketViewer';

/**
 * The full ticket thread (header + participants + messages, user view — internal messages already stripped).
 * A single cached `detail(id)` entry: the contract returns the whole thread in one call (no message
 * pagination). The viewer id (from `/me`, or the mock fallback) drives which bubbles are "mine".
 * `usePostMessage` mutates this same entry optimistically.
 */
export function useTicket(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,
  });
}
