import { useQuery } from "@tanstack/react-query"
import { supabase } from "@/lib/supabase"
import type { VocabWord, VocabTopic } from "@/types"

// Maps a Supabase row to VocabWord.
// DB column `meaning_vi` → interface field `meaningVi`.
function rowToVocabWord(row: Record<string, unknown>): VocabWord {
  return {
    id: row.id as string,
    word: row.word as string,
    phonetic: (row.phonetic as string) ?? '',
    meaningVi: row.meaning_vi as string,
    topic: row.topic as VocabTopic,
    example: (row.example as string) ?? '',
  }
}

// Fetches ALL vocab; topic filtering is done in-component so we avoid
// separate queries per topic and keep the cache simple.
export function useVocab() {
  return useQuery({
    queryKey: ['vocab'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('vocab')
        .select('*')
        .order('topic')
      if (error) throw error
      return (data ?? []).map(rowToVocabWord)
    },
  })
}
