74 lines
2.3 KiB
TypeScript
74 lines
2.3 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
import { NextRequest, NextResponse } from 'next/server'
|
|
import { createClient } from '@/lib/supabase/server'
|
|
|
|
export async function PATCH(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const supabase = await createClient()
|
|
const db = supabase as any
|
|
|
|
const { data: { user }, error: authError } = await supabase.auth.getUser()
|
|
if (authError || !user) {
|
|
return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
|
|
}
|
|
|
|
const { id } = await params
|
|
const { answer_text, is_correct } = await request.json()
|
|
|
|
// Récupérer la réponse avec sa question et le quiz pour vérifier l'ownership
|
|
const { data: answer, error: fetchError } = await db
|
|
.from('answers')
|
|
.select('id, question_id, question:questions!inner(id, quiz:quizzes!inner(author_id))')
|
|
.eq('id', id)
|
|
.single()
|
|
|
|
if (fetchError || !answer || answer.question?.quiz?.author_id !== user.id) {
|
|
return NextResponse.json({ error: 'Réponse introuvable ou accès refusé' }, { status: 404 })
|
|
}
|
|
|
|
const questionId = answer.question_id
|
|
const updates: Record<string, any> = {}
|
|
|
|
if (answer_text !== undefined) {
|
|
if (!answer_text.trim()) {
|
|
return NextResponse.json({ error: 'Texte de la réponse requis' }, { status: 400 })
|
|
}
|
|
updates.answer_text = answer_text.trim()
|
|
}
|
|
|
|
if (is_correct === true) {
|
|
// Remettre toutes les autres réponses de cette question à false
|
|
await db
|
|
.from('answers')
|
|
.update({ is_correct: false })
|
|
.eq('question_id', questionId)
|
|
.neq('id', id)
|
|
|
|
updates.is_correct = true
|
|
}
|
|
|
|
if (Object.keys(updates).length === 0) {
|
|
return NextResponse.json({ error: 'Aucune modification fournie' }, { status: 400 })
|
|
}
|
|
|
|
const { data, error } = await db
|
|
.from('answers')
|
|
.update(updates)
|
|
.eq('id', id)
|
|
.select()
|
|
.single()
|
|
|
|
if (error) {
|
|
return NextResponse.json({ error: error.message }, { status: 500 })
|
|
}
|
|
|
|
return NextResponse.json({ success: true, answer: data })
|
|
} catch (error) {
|
|
console.error('[answers/patch]', error)
|
|
return NextResponse.json({ error: 'Erreur serveur interne' }, { status: 500 })
|
|
}
|
|
}
|