import { useQuery } from '@tanstack/react-query';
import { z } from 'zod';
import { apiFetch } from '../services/apiClient';

// ---------------------------------------------------------------------------
// Zod schemas — validate API response before rendering
// ---------------------------------------------------------------------------
const DefinitionSchema = z.object({
  id: z.string().uuid(),
  text: z.string().min(1),
  date: z.string().datetime(),
  context: z.string().nullable(),
});

const WordDetailSchema = z.object({
  id: z.string().uuid(),
  text: z.string().min(1).max(255),
  createdAt: z.string().datetime(),
  status: z.enum(['active', 'to_be_defined']),
  definitions: z.array(DefinitionSchema),
});

export type WordDetail = z.infer<typeof WordDetailSchema>;
export type Definition = z.infer<typeof DefinitionSchema>;

// ---------------------------------------------------------------------------
// Fetch helper
// ---------------------------------------------------------------------------
async function fetchWordDetail(id: string): Promise<WordDetail> {
  const response = await apiFetch(`/words/${encodeURIComponent(id)}`);

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

  const raw: unknown = await response.json();
  return WordDetailSchema.parse(raw);
}

// ---------------------------------------------------------------------------
// Hook
// ---------------------------------------------------------------------------
/**
 * Fetches a single word with all its definitions.
 * Only runs when an id is provided.
 */
export function useWordDetail(id: string | null) {
  return useQuery({
    queryKey: ['words', id],
    queryFn: () => fetchWordDetail(id!),
    enabled: id !== null,
  });
}
