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

export default apiHandler({
	get: getUserReviews,
     delete: deleteUserReview, 
     post: updateUserReview,
});

async function getUserReviews(req, res) {
	if (!db.initialized) await db.initialize();

	const userID = req.userID;

	if (!userID) {
		return res.status(400).json({ error: "User ID is required" });
	}

	const userData = await db.User.findByPk(userID);
	if (!userData) {
		return res.status(404).json({ error: "User not found" });
	}

	const getReviews = await db.Reviews.findAll({
		where: {
			reviewByID: userID,
		},
		raw: true, 
	});

	const serializedReviews = await Promise.all(
		getReviews.map(async (review) => {
			const getCourseData = await db.Courses.findOne({
				attributes: ["title", "url"],
				where: {
					id: review.courseID,
				},
				raw: true,
			});

			return {
				...review,
				createdAt: new Date(review.createdAt).toISOString(),
				updatedAt: new Date(review.updatedAt).toISOString(),
				courseName: getCourseData.title,
				courseURL: getCourseData.url,
			};
		})
	);

	res.json({ reviews: serializedReviews });
}

async function deleteUserReview(req, res) {
     const userID = req.userID; 
     const reviewID = req.body; 
     
     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 (isNaN(Number(reviewID.reviewID))) {
               return res.status(404).json({ error: 'Invalid product ID!'}); 
          }

          const reviewData = await db.Reviews.findByPk(reviewID.reviewID);

          if(!reviewData) 
               return res.status(404).json({ error: 'No review found.'}); 

          if(reviewData.reviewByID != userData.id)
               return res.status(404).json({ error: 'This review is not yours.'}); 

          await db.Reviews.destroy({
               where: { id: reviewData.id }
          });
 
          return res.status(200).json({ status: 200, message: 'Ai eliminat cu success aceasta recenzie.' });
     } catch (error) {
          console.error(error); 
          return res.status(500).json({ error: 'Internal server error', status: 500 });
     }
}

async function updateUserReview(req, res) {
     const userID = req.userID;
     const { reviewID, reviewText } = req.body;
 
     if (!userID) {
         return res.status(400).json({ error: "User ID is required" });
     }
 
     if (!db.initialized) {
         await db.initialize();
     }
 
     if (!reviewID || !reviewText) {
         return res.status(400).json({ error: "Review ID and text are required" });
     }
 
     try {
          const userData = await db.User.findByPk(userID);
 
          if (!userData) {
               return res.status(404).json({ error: "User not found" });
          }
 
          const reviewData = await db.Reviews.findByPk(reviewID);
     
          if (!reviewData) {
               return res.status(404).json({ error: "No review found." });
          }
     
          if (reviewData.reviewByID !== userData.id) {
               return res.status(403).json({ error: "This review is not yours." });
          }
 
          reviewData.reviewText = reviewText;
          await reviewData.save();
 
          return res.status(200).json({ status: 200, message: "Review updated successfully." });
     } catch (error) {
          console.error(error);
          return res.status(500).json({ error: "Internal server error", status: 500 });
     }
 }