import { supabase } from '@/lib/supabase'
import type { TestRecord, PartRecord } from '@/types'

export async function fetchTests(): Promise<TestRecord[]> {
  const { data, error } = await supabase
    .from('test')
    .select('id, title, description, total_questions, duration_minutes, test_category(name)')
    .order('id')
  if (error) throw error
  return (data ?? []).map((row: Record<string, unknown>) => ({
    id: row.id as number,
    title: row.title as string,
    description: row.description as string | null,
    totalQuestions: row.total_questions as number,
    durationMinutes: row.duration_minutes as number,
    categoryName: (row.test_category as { name: string } | null)?.name ?? null,
  }))
}

export async function fetchTestWithParts(testId: number): Promise<{ test: TestRecord; parts: PartRecord[] }> {
  const { data: testRow, error: testErr } = await supabase
    .from('test')
    .select('id, title, description, total_questions, duration_minutes, test_category(name)')
    .eq('id', testId)
    .single()
  if (testErr) throw testErr

  const { data: partRows, error: partErr } = await supabase
    .from('part')
    .select('id, test_id, part_number, title, question_count')
    .eq('test_id', testId)
    .order('part_number')
  if (partErr) throw partErr

  const row = testRow as Record<string, unknown>
  return {
    test: {
      id: row.id as number,
      title: row.title as string,
      description: row.description as string | null,
      totalQuestions: row.total_questions as number,
      durationMinutes: row.duration_minutes as number,
      categoryName: (row.test_category as { name: string } | null)?.name ?? null,
    },
    parts: (partRows ?? []).map((p: Record<string, unknown>) => ({
      id: p.id as number,
      testId: p.test_id as number,
      partNumber: p.part_number as number,
      title: p.title as string,
      questionCount: p.question_count as number,
    })),
  }
}
