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

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

async function updateProductStats(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.admin < 1) {
			return res.status(401).json({ error: "Unauthorized access." });
		}

          const { productId, verified, rejectReason } = req.body;

          console.log(req.body); 

		const productData = await db.Products.findByPk(productId);

          productData.verified = verified; 
          if(verified === 2) {
               productData.rejectReason = rejectReason; 
          } else {
               productData.rejectReason = ""; 
          }

		productData.save(); 

		return res.status(201).json({
			success: true,
			message: "Produs actualizat cu succes!",
		});
	} catch (error) {
		console.error("Eroare la crearea produsului:", error);
		return res.status(500).json({ error: "Eroare la crearea produsului" });
	}
}
