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

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

async function getMarketplaceCategories(req, res) {
	if (!db.initialized) await db.initialize();

	try {
		// Preluăm toate categoriile
		const allCategories = await db.Categories.findAll({
			attributes: ["id", "name", "slug", "parentID"],
			order: [["name", "ASC"]],
		});

		// Organizăm ierarhic
		const buildHierarchy = (parentID = 0) => {
			return allCategories
				.filter((cat) => cat.parentID === parentID)
				.map((cat) => ({
					id: cat.id,
					name: cat.name,
					slug: cat.slug,
					subcategories: buildHierarchy(cat.id),
				}));
		};

		// Construim structura ierarhică pornind de la categoriile principale (parentID = 0)
		const hierarchy = buildHierarchy(0);

		// Transformăm pentru frontend (adăugăm thirdCategories pentru subcategoriile de nivel 2)
		const formatCategories = (categories) => {
			return categories.map((cat) => {
				const formatted = {
					id: cat.id,
					name: cat.name,
					slug: cat.slug,
					subcategories: [],
				};

				if (cat.subcategories && cat.subcategories.length > 0) {
					formatted.subcategories = cat.subcategories.map((sub) => ({
						id: sub.id,
						name: sub.name,
						slug: sub.slug,
						thirdCategories: sub.subcategories.map((third) => ({
							id: third.id,
							name: third.name,
							slug: third.slug,
						})),
					}));
				}

				return formatted;
			});
		};

		const formattedCategories = formatCategories(hierarchy);

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