import { useMutation, useQueryClient } from '@tanstack/react-query';
import { apiFetch } from '../services/apiClient';

interface AddDefinitionPayload {
  wordId: string;
  text: string;
  context?: string;
}

async function postDefinition({ wordId, text, context }: AddDefinitionPayload): Promise<unknown> {
  const response = await apiFetch(`/words/${encodeURIComponent(wordId)}/definitions`, {
    method: 'POST',
    body: JSON.stringify({ text, context }),
  });

  if (!response.ok) {
    throw new Error(`HTTP error ${response.status}`);
  }

  return response.json();
}

/**
 * Mutation hook to add a definition to an existing word.
 * Invalidates both the word detail and the words list on success.
 */
export function useAddDefinition() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: postDefinition,
    onSuccess: (_data, { wordId }) => {
      queryClient.invalidateQueries({ queryKey: ['words', wordId] });
      queryClient.invalidateQueries({ queryKey: ['words', 'search'] });
    },
  });
}
