11import { NextResponse } from "next/server" ;
2- import { getCurrentUser } from ' @/lib/auth' ;
2+ import { getCurrentUser } from " @/lib/auth" ;
33import { db } from "@/db" ;
4- import { quizAttempts , quizAttemptAnswers , quizQuestions , quizAnswers } from "@/db/schema/quiz" ;
4+ import {
5+ quizAttempts ,
6+ quizAttemptAnswers ,
7+ quizQuestions ,
8+ quizAnswers ,
9+ } from "@/db/schema/quiz" ;
510import { awardQuizPoints , calculateQuizPoints } from "@/db/queries/points" ;
611import { eq , inArray } from "drizzle-orm" ;
712
@@ -17,23 +22,25 @@ export async function POST(req: Request) {
1722 ) ;
1823 }
1924
20- const { userId , quizId, answers, violations, timeSpentSeconds } = body ;
25+ const { quizId, answers, violations, timeSpentSeconds } = body ;
2126
22- if ( ! userId || ! quizId || ! Array . isArray ( answers ) || answers . length === 0 ) {
27+ if ( ! quizId || ! Array . isArray ( answers ) || answers . length === 0 ) {
2328 return NextResponse . json (
2429 { success : false , error : "Invalid input" } ,
2530 { status : 400 }
2631 ) ;
2732 }
2833
2934 const session = await getCurrentUser ( ) ;
30- if ( ! session || session . id !== userId ) {
35+ if ( ! session ) {
3136 return NextResponse . json (
3237 { success : false , error : "Unauthorized" } ,
3338 { status : 401 }
3439 ) ;
3540 }
3641
42+ const userId = session . id ;
43+
3744 const questionRows = await db
3845 . select ( { id : quizQuestions . id } )
3946 . from ( quizQuestions )
@@ -114,14 +121,13 @@ export async function POST(req: Request) {
114121 ) ;
115122 }
116123
117- const isCorrect = record . isCorrect ;
118- if ( isCorrect ) correctAnswersCount ++ ;
124+ if ( record . isCorrect ) correctAnswersCount ++ ;
119125
120126 attemptAnswers . push ( {
121127 attemptId : "" ,
122128 quizQuestionId : answer . questionId ,
123129 selectedAnswerId : answer . selectedAnswerId ,
124- isCorrect,
130+ isCorrect : record . isCorrect ,
125131 answeredAt : now ,
126132 } ) ;
127133 }
@@ -132,10 +138,12 @@ export async function POST(req: Request) {
132138 const integrityScore = Math . max ( 0 , 100 - violationsArray . length * 10 ) ;
133139 const safeTimeSpentSeconds = Math . max ( 0 , Number ( timeSpentSeconds ) || 0 ) ;
134140 const startedAt = new Date ( now . getTime ( ) - safeTimeSpentSeconds * 1000 ) ;
141+
135142 const pointsEarned = calculateQuizPoints ( {
136143 score : correctAnswersCount ,
137144 integrityScore,
138145 } ) ;
146+
139147 try {
140148 const [ attempt ] = await db
141149 . insert ( quizAttempts )
@@ -185,4 +193,4 @@ export async function POST(req: Request) {
185193 { status : 500 }
186194 ) ;
187195 }
188- }
196+ }
0 commit comments