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

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

async function updateCourseProgress(req, res) {
     const userID = req.userID;
     const { seconds, lessonName, 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 (!parseInt(seconds)) {
          return res.status(404).json({ error: "Invalid seconds val!" });
     }

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

     const courseData = await db.Courses.findByPk(courseID);
 
     if (!courseData) 
          return res.status(404).json({ error: "No course found." });

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

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

     const jsonProgress = JSON.parse(courseProgress.courseProgress); 

     const updatedProgress = jsonProgress.map((lesson) => {
          if (lesson.name === lessonName) {
              
               const updatedWatchedSeconds = Math.max(Number(lesson.watchedSeconds) || 0, Number(seconds) || 0); 
               return {
                    ...lesson,
                    watchedSeconds: updatedWatchedSeconds,
                    completed: updatedWatchedSeconds >= lesson.neededSeconds, 
               };
          }
          return lesson;
     });


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