import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { ticketsApi } from '../apis';
import { ticketKeys } from '../keys';
import { TICKETS_GC_TIME, TICKETS_LIST_STALE_TIME, TICKETS_PAGE_SIZE } from '../constants';
import type { TicketListParams } from '../types';

/**
 * The "My Tickets" inbox — the caller's own tickets, newest-activity first, optionally narrowed by status.
 * The **filter object keys the cache**, so paging/filtering caches independently and revisiting the inbox
 * serves from cache; `keepPreviousData` avoids a flash on a status change. Opening a ticket or posting a
 * message invalidates `tickets.lists()`, so new activity shows without a manual refresh.
 */
export function useMyTickets(params: TicketListParams = {}) {
  const listParams: TicketListParams = { page: params.page ?? 1, pageSize: params.pageSize ?? TICKETS_PAGE_SIZE, status: params.status };
  return useQuery({
    queryKey: ticketKeys.list(listParams),
    queryFn: () => ticketsApi.listMyTickets(listParams),
    placeholderData: keepPreviousData,
    staleTime: TICKETS_LIST_STALE_TIME,
    gcTime: TICKETS_GC_TIME,
  });
}
