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

export default apiHandler({
     get: getInstructorStats
});

async function getInstructorStats(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!' });

          if(userData.accountType != 1)
               return res.status(401).json({ error: 'Unauthorized!'}); 

          const totalCourses = await db.Courses.findAll({
               attributes:['id', 'title', 'url'], 
               where: {
                    instructorID: userID
               },
               raw: true
          });

          const courseIDs = totalCourses.map(course => course.id);
          const courseNames = totalCourses.map(course => course.title); 

          const totalStudents = await db.CoursesProgress.count({
               where: {
                    courseID: {
                         [Op.in]: courseIDs 
                    }
               }
          });

          const totalEarnings = await db.Orders.sum('price', {
               where: {
                    courseName: {
                         [Op.in]: courseNames
                    }
               }
          });
          
          const tableCourses = await Promise.all(
               totalCourses.map(async (course) => {
                    const studentCount = await db.CoursesProgress.count({
                         where: {
                              courseID: course.id
                         }
                    });

                    const reviews = await db.Reviews.findAll({
                         attributes: ['reviewStars', 'reviewBy', 'reviewText'],
                         where: {
                             courseID: course.id
                         },
                         raw: true
                    });

                    const totalReviews = reviews.length;
                    const averageStars = totalReviews > 0 
                         ? (reviews.reduce((sum, review) => sum + review.reviewStars, 0) / totalReviews).toFixed(1)
                         : null; 

                    return {
                         url: course.url, 
                         title: course.title,
                         students: studentCount,
                         averageStars: averageStars,
                         reviews: reviews
                    };
               })
          );

          const response = {
               totalCourses: courseIDs.length,
               totalStudents: totalStudents, 
               totalEarnings: totalEarnings,
               coursesTable: tableCourses
          };
          console.log(response); 
          return res.status(200).json(response);
     } catch (error) {
          return res.status(500).json({ error: 'Eroare la preluarea datelor utilizatorului.' });
     }
}