import { supabase } from '@/lib/supabase'

interface TestResultData {
  partId: number
  partName: string
  score: number
  total: number
  timeUsed: number
  answers: { questionId: string; selected: number | null; correct: boolean }[]
}

/** Fire-and-forget: save test result. Failures are logged but don't block UI. */
export async function saveTestResult(userId: string, data: TestResultData): Promise<void> {
  const { error } = await supabase.from('user_progress').insert({
    user_id: userId,
    type: 'test',
    data,
  })
  if (error) console.error('Failed to save test result:', error.message)
}

/** Fire-and-forget: save writing submission with AI feedback. */
export async function saveWritingSubmission(
  userId: string,
  content: string,
  feedback: object,
): Promise<void> {
  const { error } = await supabase.from('writing_submissions').insert({
    user_id: userId,
    content,
    feedback,
  })
  if (error) console.error('Failed to save writing submission:', error.message)
}

/** Count today's writing submissions for server-side rate limiting (authenticated users). */
export async function countTodayWritingSubmissions(userId: string): Promise<number> {
  const today = new Date().toISOString().split('T')[0]
  const { count, error } = await supabase
    .from('writing_submissions')
    .select('*', { count: 'exact', head: true })
    .eq('user_id', userId)
    .gte('created_at', `${today}T00:00:00.000Z`)
  if (error) return 0
  return count ?? 0
}

/** Fetch test history for a user (most recent first, max 20). */
export async function fetchTestHistory(userId: string) {
  const { data, error } = await supabase
    .from('user_progress')
    .select('*')
    .eq('user_id', userId)
    .eq('type', 'test')
    .order('created_at', { ascending: false })
    .limit(20)
  if (error) throw error
  return data ?? []
}

/** Fetch writing history for a user (most recent first, max 20). */
export async function fetchWritingHistory(userId: string) {
  const { data, error } = await supabase
    .from('writing_submissions')
    .select('id, content, feedback, created_at')
    .eq('user_id', userId)
    .order('created_at', { ascending: false })
    .limit(20)
  if (error) throw error
  return data ?? []
}
