import { NextRequest, NextResponse } from 'next/server'; import { createClient } from '@/utils/supabase/server'; interface QuizData { teamName: string; answer: string; questionNumber: number; quizId: number | null; } export async function POST(req: NextRequest) { try { const webhookUrl = process.env.DISCORD_QUIZ_WEBHOOK_URL; const supabase = createClient(); // Handle the case where webhookUrl is not set if (!webhookUrl) { console.error('Discord webhook URL is not set in environment variables.'); return NextResponse.json( { message: 'Server error: Discord webhook URL is not configured.' }, { status: 500 } ); } const data: QuizData = await req.json(); // Validate required fields const { teamName, answer, questionNumber, quizId } = data; if (!teamName || !answer || questionNumber === undefined) { return NextResponse.json( { message: 'Bad request: Missing required quiz data.' }, { status: 400 } ); } // Save the answer to Supabase if quizId is provided if (quizId) { try { const { error } = await supabase.from('quiz_answers').insert({ team_name: teamName, question_number: questionNumber, answer: answer, quiz_id: Number(quizId), correct: false, points: 0 }); if (error) { console.error('Error saving answer to Supabase:', error); } } catch (supabaseError) { console.error('Supabase insertion error:', supabaseError); } } // Construct the plain text message content with quiz ID const quizIdText = quizId ? `Quiz ${quizId}` : 'Unknown Quiz'; const messageContent = `${quizIdText} | ${teamName} | Q ${questionNumber} | ${answer}`; // Send the message to Discord via the webhook const discordResponse = await fetch(webhookUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ content: messageContent, // Use content field for plain text messages username: 'Quiz Bot', // Optional: Set the username of the bot avatar_url: 'https://www.vkashti.bar/logo.png' // Optional: Set the avatar of the bot }) }); if (!discordResponse.ok) { console.error( 'Failed to send message to Discord webhook:', discordResponse.statusText ); return NextResponse.json( { message: 'Error sending message to Discord.' }, { status: 500 } ); } return NextResponse.json({ message: 'Success' }, { status: 200 }); } catch (error) { console.error('Error:', error); return NextResponse.json({ message: 'Server error.' }, { status: 500 }); } }