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

export default apiHandler({
     get: getUserCourses
});

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

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

     try {
          console.log('Fetching user data for userID:', userID);
          const userData = await db.User.findByPk(userID);

          if (!userData) {
               console.log('User not found for userID:', userID);
               return res.status(404).json({ error: 'Unknown!' });
          }

          if (userData.accountType != 0) {
               console.log('Unauthorized access attempt by userID:', userID);
               return res.status(401).json({ error: 'Unauthorized!' });
          }

          console.log('Fetching courses progress for userID:', userID);
          const studentCourses = await db.CoursesProgress.findAll({
               where: {
                   userID: userData.id 
               },
               raw: true
          });

          console.log('Processing courses progress...');
          const uncompleted = []; 
          const completed = [];
           
          studentCourses.forEach(course => {
               console.log('Processing course:', course.courseID);

               // Assuming courseProgress is already an object
               const courseProgress = typeof course.courseProgress === 'string' 
                    ? JSON.parse(course.courseProgress)
                    : course.courseProgress;

               const totalLessons = courseProgress.length;
               const completedLessons = courseProgress.filter(lesson => lesson.completed).length;
           
               const completionPercentage = (completedLessons / totalLessons) * 100;
           
               if (completedLessons === totalLessons) {
                    completed.push({
                         ...course,
                         completionPercentage
                    });
               } else {
                    uncompleted.push({
                         ...course,
                         completionPercentage
                    });
               }
          });

          console.log('Completed processing courses');
          return res.status(200).json({
               uncompletedCourses: uncompleted, 
               completedCourses: completed
          });
     } catch (error) {
          console.error('Error in getUserCourses:', error);
          return res.status(500).json({ error: 'Eroare la preluarea datelor utilizatorului.' });
     }
}
