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

export default apiHandler({
     get: getStudentCourses
});

async function getStudentCourses(req, res) {
     const userID = req.userID;

     if(!db.initialized)
          await db.initialize(); 

     try {
          const userData = await db.User.findByPk(userID); 
          
          if (!userData) 
               return res.status(404).json({ error: 'Unknown!' });

          const boughtCourses = await db.Orders.count({
               where: {
                    userID: userData.id
               }
          });
     
          const studentCourses = await db.CoursesProgress.findAll({
               where: {
                   userID: userData.id 
               },
               raw: true
          });

          let uncompleted = 0; 
          let completed = 0;
           
          studentCourses.forEach(course => {
               const courseProgress = typeof course.courseProgress === 'string' 
                    ? JSON.parse(course.courseProgress)
                    : course.courseProgress;

               const totalLessons = courseProgress.length;
               const completedLessons = courseProgress.filter(lesson => lesson.completed).length;
           
               if (completedLessons === totalLessons) {
                    completed ++; 
               } else {
                    uncompleted ++; 
               }
          }); 

          const response = {
               boughtCourses: boughtCourses,
               completedCourses: completed, 
               uncompletedCourses: uncompleted
          };

          console.log(response); 
          return res.status(200).json(response);
     } catch (error) {
          return res.status(500).json({ error: 'Eroare la preluarea datelor utilizatorului.' });
     }
}