import { apiHandler, db } from "@/helpers/api";

export default apiHandler({
	post: updateQuiz,
});

async function updateQuiz(req, res) {
     const userID = req.userID;
     const { moduleID, courseID } = req.body;
 
     if (!userID) {
         return res.status(400).json({ error: "User ID is required" });
     }
 
     if (!db.initialized) {
         await db.initialize();
     }

     const userData = await db.User.findByPk(userID);
 
     if (!userData) 
        return res.status(404).json({ error: "User not found" });

     if (!moduleID || isNaN(Number(moduleID))) 
          return res.status(404).json({ error: "Invalid module ID!" });

     const moduleData = await db.Modules.findByPk(moduleID);
 
     if (!moduleData) 
          return res.status(404).json({ error: "No module found." });

     const courseProgress = await db.CoursesProgress.findOne({
          attributes:['quizProgress'], 
          where: {
               userID: userID, 
               courseID: courseID, 
          },
          raw: true,
          limit: 1,
     });

     if (!courseProgress || !courseProgress.quizProgress) {
          return res.status(404).json({ error: "Course progress not found." });
     }

     const actualProgress = JSON.parse(courseProgress.quizProgress); 
     console.log(actualProgress); 

     const updatedProgress = actualProgress.map((quiz) => {
          console.log('quizmodule:'+quiz.module);
          console.log('moduleid: ' + moduleID); 

          if (parseInt(quiz.module) === parseInt(moduleID)) {
               console.log("aici lucrez");
               const newQuiz = {
                    ...quiz,
                    quizCompleted: true,
               };
               console.log(newQuiz); 
               return {
                    ...quiz,
                    quizCompleted: true,
               };
          }
          return quiz;
     });


     await db.CoursesProgress.update(
          { quizProgress: JSON.stringify(updatedProgress) },
          {
              where: {
                  userID: userID,
                  courseID: courseID,
              },
              limit: 1,
          }
      );
  
     res.status(200).json({ message: "Quiz progress updated successfully." });
}