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

export default apiHandler({
	get: getStats,
});

async function getStats(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 totalOrders = await db.Orders.findAll({
			attributes: ["items"],
			where: {
				status: "paid",
				createdAt: {
					[Op.gte]: new Date(new Date().getFullYear(), new Date().getMonth(), 1),
				},
			},

		});

          const parseItems = (items) => {
               if (!items) return [];
               if (typeof items === "string") {
                    try {
                         return JSON.parse(items);
                    } catch {
                         return [];
                    }
               }
               if (Array.isArray(items)) return items;
               return [];
          };

		const totalSalesThisMonth = totalOrders.reduce((sum, order) => {
			let items = [];
			try {
				items = parseItems(order.items);
			} catch (e) {
				console.error("Eroare la parsarea items:", e);
			}

			const orderTotal = items.reduce((orderSum, item) => {
				return orderSum + item.price * item.quantity;
			}, 0);

			return sum + orderTotal;
		}, 0);

          const totalReturnsThisMonth = await db.Returns.count({
               where: {
                    createdAt: {
                         [Op.gte]: new Date(new Date().getFullYear(), new Date().getMonth(), 1),
                    }
               }
          });

		return res.status(200).json({
			totalSalesThisMonth: totalSalesThisMonth.toFixed(2),
               totalOrdersThisMonth: totalOrders.length,
               totalProducts: await db.Products.count(),
               totalReturnsThisMonth: totalReturnsThisMonth
 		});
	} catch (error) {
		console.error("Eroare la preluarea statisticilor:", error);
		return res.status(500).json({ error: "Eroare la preluarea statisticilor" });
	}
}
