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

interface PostMessageVars {
  body: string;
  /** Client-generated id; the reconcile key so the optimistic bubble is never double-rendered (§3.5). */
  clientMessageId: string;
}

interface PostMessageContext {
  previous?: TicketDetail;
}

/**
 * The optimistic message send — the interaction that must feel instant (phase §3.5).
 *
 * `onMutate` appends a **pending** bubble to `detail(id)` (after `cancelQueries` + a snapshot) so it shows
 * immediately with a "sending" state. `onError` **rolls the thread back to the snapshot** (removing the
 * pending bubble) and rejects — the composer keeps the typed draft and offers retry (never retype). `onSuccess`
 * replaces the pending bubble **by `clientMessageId`** with the server message (so it never double-renders).
 * `onSettled` invalidates the thread + the inbox lists (last-activity/unread move). The composer clears the
 * draft **only** in its own `onSuccess`.
 */
export function usePostMessage(ticketId: number) {
  const queryClient = useQueryClient();
  const { role } = useTicketViewer();

  return useMutation<PostMessageResult, unknown, PostMessageVars, PostMessageContext>({
    mutationFn: ({ body, clientMessageId }) => ticketsApi.postMessage(ticketId, { body, clientMessageId }),

    onMutate: async ({ body, clientMessageId }) => {
      const key = ticketKeys.detail(ticketId);
      await queryClient.cancelQueries({ queryKey: key });
      const previous = queryClient.getQueryData<TicketDetail>(key);
      if (previous) {
        const pending: TicketMessage = {
          id: null,
          clientMessageId,
          ticketId,
          body,
          authorRole: role,
          createdAt: new Date().toISOString(),
          isMine: true,
          sendStatus: 'sending',
        };
        queryClient.setQueryData<TicketDetail>(key, { ...previous, messages: [...previous.messages, pending] });
      }
      return { previous };
    },

    onError: (_err, _vars, context) => {
      if (context?.previous) queryClient.setQueryData(ticketKeys.detail(ticketId), context.previous);
    },

    onSuccess: (result, { clientMessageId }) => {
      const key = ticketKeys.detail(ticketId);
      const current = queryClient.getQueryData<TicketDetail>(key);
      if (current) {
        queryClient.setQueryData<TicketDetail>(key, {
          ...current,
          messages: current.messages.map((m) =>
            m.clientMessageId === clientMessageId
              ? { ...m, id: result.messageId, createdAt: result.sentAt, sendStatus: 'sent' }
              : m,
          ),
        });
      }
    },

    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ticketKeys.detail(ticketId) });
      queryClient.invalidateQueries({ queryKey: ticketKeys.lists() });
    },
  });
}
