import { useMutation, useQueryClient } from '@tanstack/react-query';
import { ticketsApi } from '../apis';
import { ticketKeys } from '../keys';
import type { OpenTicketRequest, OpenTicketResult } from '../types';
import { useTicketViewer } from './useTicketViewer';

/**
 * Open a ticket (support / coordination from a booking / …). We pass the viewer id so the mock attributes the
 * opening message to the right actor (a nurse-opened ticket's first message renders as the nurse's, not the
 * customer's). On success we invalidate the inbox lists so the new ticket appears at the top without a manual
 * refresh (phase §7 step 1). Domain 4xx (e.g. a `403` on a disallowed booking link) surface to the caller's
 * `onError`; the dialog keeps the draft.
 */
export function useOpenTicket() {
  const queryClient = useQueryClient();
  const { userId } = useTicketViewer();
  return useMutation<OpenTicketResult, unknown, OpenTicketRequest>({
    mutationFn: (body) => ticketsApi.openTicket(body, userId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ticketKeys.lists() });
    },
  });
}
