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

const ANSWER_INDEX: Record<string, number> = { A: 0, B: 1, C: 2, D: 3 }

// Maps a Supabase row to the shared Question interface.
// DB uses `content` + `answer` ('A'–'D'); interface uses `text` + `correctAnswer` (0–3).
function rowToQuestion(row: Record<string, unknown>): Question {
  return {
    id: row.id as string,
    part: row.part as number,
    text: row.content as string,
    options: row.options as string[],
    correctAnswer: ANSWER_INDEX[(row.answer as string).toUpperCase()] ?? 0,
    explanation: (row.explanation as string) ?? '',
  }
}

// Exported for imperative use (e.g. ToeicPractice click handler).
// part=0 fetches all parts (Full Test).
export async function fetchQuestions(part: number, limit = 10): Promise<Question[]> {
  let query = supabase.from('questions').select('*').limit(limit)
  if (part > 0) query = query.eq('part', part)
  const { data, error } = await query
  if (error) throw error
  return (data ?? []).map(rowToQuestion)
}

export function useQuestions(part: number, limit = 10) {
  return useQuery({
    queryKey: ['questions', part, limit],
    queryFn: () => fetchQuestions(part, limit),
  })
}
