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

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

async function postReview(req, res) {
     const userID = req.userID;
     const { reviewText, reviewStars, 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(reviewStars)) {
          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." });
     }

     await db.Reviews.create(
          {
               reviewBy: userData.userName, 
               reviewByID: userID, 
               courseID: courseID, 
               reviewStars: parseInt(reviewStars), 
               reviewText: reviewText 

          }
     );
  
     res.status(200).json({ message: "Review added successfully." });
}