// /api/categories/main.js
import { db } from "@/helpers/api/db";

export default async function handler(req, res) {
	if (req.method !== "GET") {
		return res.status(405).json({ error: "Method not allowed" });
	}

	if (!db.initialized) {
		await db.initialize();
	}

	try {
		const mainCategories = await db.Categories.findAll({
			where: { parentID: 0 },
			attributes: [
				"id", 
				"name", 
                    "name_en",
                    "name_it",
                    "name_fr",
                    "name_de", 
				"slug", 
				"title",
				// Count produse bazat pe slug
				[
					db.sequelize.literal(`(
						SELECT COUNT(*)
						FROM products p
						WHERE p.categorySlug = categories.slug AND p.visible = 1
					)`),
					'productCount'
				]
			],
			order: [["id", "ASC"]],
		});

		return res.status(200).json({
			categories: mainCategories,
			total: mainCategories.length,
		});
	} catch (error) {
		console.error("Error fetching main categories:", error);
		return res.status(500).json({
			error: "Internal server error",
			status: 500,
		});
	}
}