corenthin-lebreton 28aa3b0e10 initial project
2026-02-26 20:10:14 +01:00

89 lines
2.5 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { calculateScore } from '@/lib/utils'
export async function POST(request: NextRequest) {
try {
const supabase = await createClient()
const db = supabase as any
const body = await request.json()
const { participation_id } = body
if (!participation_id) {
return NextResponse.json({ error: 'participation_id est requis' }, { status: 400 })
}
const { data: participation, error: partError } = await db
.from('student_participations')
.select('id, status, session_id')
.eq('id', participation_id)
.single()
if (partError || !participation) {
return NextResponse.json({ error: 'Participation introuvable' }, { status: 404 })
}
if (participation.status === 'completed') {
return NextResponse.json({ error: 'Ce quiz est déjà terminé' }, { status: 400 })
}
const { data: session } = await db
.from('sessions')
.select('quiz_id')
.eq('id', participation.session_id)
.single()
if (!session) {
return NextResponse.json({ error: 'Session introuvable' }, { status: 404 })
}
const { count: totalQuestions } = await db
.from('questions')
.select('id', { count: 'exact', head: true })
.eq('quiz_id', session.quiz_id)
const { data: correctAnswers } = await db
.from('student_answers')
.select(`id, answers!inner(is_correct)`)
.eq('participation_id', participation_id)
.eq('answers.is_correct', true)
const N: number = totalQuestions ?? 0
const C: number = correctAnswers?.length ?? 0
const score = calculateScore(C, N)
const { data: updatedParticipation, error: updateError } = await db
.from('student_participations')
.update({
status: 'completed',
score,
completed_at: new Date().toISOString(),
})
.eq('id', participation_id)
.select()
.single()
if (updateError || !updatedParticipation) {
return NextResponse.json(
{ error: 'Erreur mise à jour de la participation', details: updateError?.message },
{ status: 500 }
)
}
return NextResponse.json({
success: true,
result: {
score,
correct: C,
total: N,
status: 'completed',
},
})
} catch (error) {
console.error('[student/finish]', error)
return NextResponse.json({ error: 'Erreur serveur interne' }, { status: 500 })
}
}