import { useQueryClient } from '@tanstack/react-query';
import { ticketKeys } from '../keys';
import type { TicketDetail } from '../types';

/**
 * The composer's "discard and retype" affordance on a failed bubble (§3.3) — removes it from the cached
 * thread so the caller can restore its text into the composer draft. Not a mutation: a message that never
 * left the client has nothing to tell the server.
 */
export function useDiscardFailedMessage() {
  const queryClient = useQueryClient();
  return (ticketId: number, clientMessageId: string): void => {
    const key = ticketKeys.detail(ticketId);
    queryClient.setQueryData<TicketDetail>(key, (current) =>
      current
        ? { ...current, messages: current.messages.filter((m) => m.clientMessageId !== clientMessageId) }
        : current,
    );
  };
}
