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

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

async function getCategories(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 categories = await db.Categories.findAll({
			order: [["name", "ASC"]],
			raw: true,
		});

		// Organizează categoriile ierarhic
		const categoriesMap = {};
		const rootCategories = [];

		categories.forEach((cat) => {
			categoriesMap[cat.id] = { ...cat, children: [] };
		});

		categories.forEach((cat) => {
			if (cat.parentID && categoriesMap[cat.parentID]) {
				categoriesMap[cat.parentID].children.push(categoriesMap[cat.id]);
			} else if (!cat.parentID) {
				rootCategories.push(categoriesMap[cat.id]);
			}
		});

		return res.status(200).json({
			categories: rootCategories,
			allCategories: categories,
		});
	} catch (error) {
		console.error("Eroare la preluarea categoriilor:", error);
		return res.status(500).json({ error: "Eroare la preluarea categoriilor" });
	}
}
