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

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

async function getUsers(req, res) {
	const userID = req.userID;
	const { 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." });
		}

		let whereClause = {};

		if (search) {
			whereClause = {
				[Op.or]: [
					{ email: { [Op.like]: `%${search}%` } },
					{ firstName: { [Op.like]: `%${search}%` } },
					{ lastName: { [Op.like]: `%${search}%` } },
				],
			};
		}

		const users = await db.User.findAll({
			where: whereClause,
			attributes: ["id", "email", "firstName", "lastName", "admin", "createdAt", "updatedAt"],
			order: [["id", "DESC"]],
		});

		// Obține numărul de comenzi pentru fiecare utilizator
		const usersWithOrders = await Promise.all(
			users.map(async (user) => {
				const ordersCount = await db.Orders.count({
					where: { userID: user.id },
				});

				return {
					...user.toJSON(),
					ordersCount,
				};
			})
		);

		return res.status(200).json({ users: usersWithOrders });
	} catch (error) {
		console.error("Eroare la obținerea utilizatorilor:", error);
		return res.status(500).json({ error: "Eroare la obținerea utilizatorilor" });
	}
}
