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

export default apiHandler({
	get: getCourseData,
});

async function getCourseData(req, res) {
     const userID = req.userID;
     const { courseID } = req.query;
 
     if (!userID) {
         return res.status(400).json({ error: "User ID is required" });
     }
 
     if (!db.initialized) {
         await db.initialize();
     }
 
     try {
          const userData = await db.User.findByPk(userID);
 
          if (!userData) 
             return res.status(404).json({ error: "User not found" });
 
          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 coursesProgress = await db.CoursesProgress.findOne({
               where: {
                    courseID: courseID,
               },
               limit: 1,
               raw: true,
          });
         
          if (coursesProgress.userID !== userData.id) {
               return res.status(404).json({ error: "This course is not yours." });
          }
 
          const modules = await db.Modules.findAll({
               where: {
                    courseID: courseID, 
               },
               raw: true,
          });

          const progressEntries  = await db.CoursesProgress.findAll({
               where: {
                    courseID: courseID, 
                    userID: userData.id
               },
               raw:true,
               limit: 1
          });

          const courseContent = await Promise.all(modules.map(async (module) => {
               const lessons = await db.Modules.findAll({
                    where: {
                         parentID: module.id,
                         type:'lesson'
                    },
                    raw: true,
               });

               const progress = progressEntries.length > 0 ? JSON.parse(progressEntries[0].courseProgress) : [];
               const progress2 = progressEntries.length > 0 ? JSON.parse(progressEntries[0].quizProgress) : []; 

               const updatedLessons = lessons.map(lesson => {
                    const lessonProgress = progress.find(item => item.name === lesson.title) || {};
                    return {
                         ...lesson,
                         completed: lessonProgress.completed || false,
                         watchedSeconds: lessonProgress.watchedSeconds || 0,
                    };
               });
           
               const quizProgress = progress2.find(item => parseInt(item.module) === parseInt(module.id)) ?? null;
              
               return {
                   ...module,
                   listItem: updatedLessons,
                   quizProgress:quizProgress,
               };
          }));
 
          const responseData = {
               courseName: courseData.title,
               courseContent: courseContent,
          };
 
          return res.status(200).json(responseData);
     } catch (error) {
          console.error(error);
          return res
               .status(500)
               .json({ error: "Internal server error", status: 500 });
     }
}
