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

interface CreateWordPayload {
  text: string;
  definition?: string;
}

async function postWord(payload: CreateWordPayload): Promise<unknown> {
  const response = await apiFetch('/words', {
    method: 'POST',
    body: JSON.stringify(payload),
  });

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

  return response.json();
}

/**
 * Mutation hook to create a word with an optional first definition.
 * Invalidates the 'words' query cache on success.
 */
export function useCreateWord() {
  const queryClient = useQueryClient();

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