// pages/api/admin/orders/list.js
import { apiHandler, db } from "@/helpers/api";

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

async function getOrders(req, res) {
	const userID = req.userID;
	const { page = 1, limit = 10, status, search } = req.query;

	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 { Op } = require("sequelize");

		let whereClause = {};

		// Filtrare după status
		if (status && status !== "all") {
			whereClause.status = status;
		}

		// Căutare
		if (search) {
			whereClause[Op.or] = [
				{ pf_prenume: { [Op.like]: `%${search}%` } },
				{ pf_nume_familie: { [Op.like]: `%${search}%` } },
				{ pf_email: { [Op.like]: `%${search}%` } },
				{ pj_nume_firma: { [Op.like]: `%${search}%` } },
				{ pj_email: { [Op.like]: `%${search}%` } },
			];
		}

		const offset = (parseInt(page) - 1) * parseInt(limit);

		// Query pentru comenzi - FĂRĂ include
		const orders = await db.Orders.findAll({
			where: whereClause,
			order: [["id", "DESC"]],
			limit: parseInt(limit),
			offset: offset,
		});

		// Query separat pentru count
		const count = await db.Orders.count({
			where: whereClause,
		});

		// Procesare date comenzi
		const processedOrders = await Promise.all(
			orders.map(async (order) => {
				const orderData = order.toJSON();

				// Parse items din JSON
				let items = [];
				try {
					items = typeof orderData.items === "string" ? JSON.parse(orderData.items) : orderData.items;
				} catch (e) {
					items = [];
				}

				// Calculează totalul
				const total = items.reduce((sum, item) => {
					return sum + parseFloat(item.price) * parseInt(item.quantity);
				}, 0);

				// Determină numele clientului
				let customerName = "";
				let customerEmail = "";

				if (orderData.billingType === 0) {
					// Persoană fizică
					customerName = `${orderData.pf_prenume} ${orderData.pf_nume_familie}`;
					customerEmail = orderData.pf_email;
				} else {
					// Persoană juridică
					customerName = orderData.pj_nume_firma;
					customerEmail = orderData.pj_email;
				}

				// Query separat pentru User dacă există userID
				let user = null;
				if (orderData.userID && orderData.userID > 0) {
					try {
						const userRecord = await db.User.findByPk(orderData.userID, {
							attributes: ["id", "email", "firstName", "lastName"],
						});
						user = userRecord ? userRecord.toJSON() : null;
					} catch (e) {
						console.error(`Error fetching user ${orderData.userID}:`, e.message);
						user = null;
					}
				}

				return {
					id: orderData.id,
					customerName,
					customerEmail,
					billingType: orderData.billingType,
					status: orderData.status,
					total: total.toFixed(2),
					itemsCount: items.length,
					items: items,
					createdAt: orderData.createdAt,
					updatedAt: orderData.updatedAt,
					user: user,
				};
			})
		);

		const totalPages = Math.ceil(count / parseInt(limit));

		return res.status(200).json({
			orders: processedOrders,
			pagination: {
				currentPage: parseInt(page),
				totalPages,
				totalItems: count,
				itemsPerPage: parseInt(limit),
			},
		});
	} catch (error) {
		console.error("Eroare la obținerea comenzilor:", error);
		return res.status(500).json({ error: "Eroare la obținerea comenzilor" });
	}
}