import { keepPreviousData, useQuery } from '@tanstack/react-query';
import type { PageParams } from '@/lib/api/types';
import { ticketsApi } from '../apis';
import { ticketKeys } from '../keys';
import { ADMIN_TICKETS_LIST_STALE_TIME, TICKETS_GC_TIME, TICKETS_PAGE_SIZE } from '../constants';
import type { AdminTicketFilters } from '../types';

/**
 * The admin global ticket queue (b15 `GET /admin/tickets`) — EVERY ticket, not one viewer's, filterable by
 * status/category/referenceCode/bookingId/refundId. The **filter object + page key the cache**, so each
 * filter/page combination caches independently and revisiting serves from cache; `keepPreviousData` avoids a
 * flash while a filter changes. Posting an admin message invalidates `adminLists()`, so new activity shows
 * without a manual refresh.
 */
export function useAdminTickets(filters: AdminTicketFilters = {}, page = 1) {
  const params: PageParams = { page, pageSize: TICKETS_PAGE_SIZE };
  return useQuery({
    queryKey: ticketKeys.adminList(filters, params),
    queryFn: () => ticketsApi.listAdminTickets(filters, params),
    placeholderData: keepPreviousData,
    staleTime: ADMIN_TICKETS_LIST_STALE_TIME,
    gcTime: TICKETS_GC_TIME,
  });
}
