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

interface UpdateDefinitionPayload {
  wordId: string;
  definitionId: string;
  /** Update context (pass null to clear) */
  context?: string | null;
  /** Update the definition text */
  text?: string;
}

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

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

  return response.json();
}

/**
 * Mutation hook to update the context of a definition.
 * Invalidates the word detail cache on success.
 */
export function useUpdateDefinition() {
  const queryClient = useQueryClient();

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