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

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

async function getOrders(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.statsu(401).json({ error: "Unauthorized access." });
		}

		// Extrage parametrii de paginare din query string
		const page = parseInt(req.query.page) || 1;
		const limit = parseInt(req.query.limit) || 10; // default 10
		const offset = (page - 1) * limit;

		// Preia comenzile cu paginare
		const { count, rows: orders } = await db.Orders.findAndCountAll({
			order: [["createdAt", "DESC"]],
			limit: limit,
			offset: offset,
			raw: true,
		});

          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 ordersWithTotal = orders.map((order) => {
			let items = [];
			try {
				items = parseItems(order.items); 
			} catch (e) {
				console.error("Eroare la parsarea items:", e);
			}

               

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

			return {
				...order,
				total,
			};
		});

		// Calculează informații despre paginare
		const totalPages = Math.ceil(count / limit);
		const hasNextPage = page < totalPages;
		const hasPrevPage = page > 1;

		return res.status(200).json({
			orders: ordersWithTotal,
			pagination: {
				currentPage: page,
				totalPages: totalPages,
				totalItems: count,
				itemsPerPage: limit,
				hasNextPage: hasNextPage,
				hasPrevPage: hasPrevPage,
			},
		});
	} catch (error) {
		return res.status(500).json({ error: "Eroare la preluarea comenzilor." });
	}
}
