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

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

	try {
		const { slug } = req.query;

		const slugArray = Array.isArray(slug) ? slug : [slug];

		if (!slugArray || slugArray.length === 0 || slugArray.length > 3) {
			return res.status(400).json({ error: "Invalid slug" });
		}

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

		console.log('Searching for categories with slugs:', slugArray);

		// Căutăm fiecare categorie individual pentru a respecta ierarhia
		const categoryPromises = slugArray.map((categorySlug, index) => 
			db.Categories.findOne({
				attributes: ["name", "name_en", "name_it", "name_fr", "name_de", "slug", "description"],
				where: { slug: categorySlug },
				raw: true,
			})
		);

		const categories = await Promise.all(categoryPromises);
		const validCategories = categories.filter(cat => cat !== null);

		console.log('Found categories:', validCategories.length);

		if (validCategories.length === 0) {
			return res.status(404).json({ productsData: false });
		}

		// Construim whereClause pentru produse bazat pe câte categorii am găsit
		const whereClause = {};

		if (validCategories.length > 0) whereClause.categorySlug = validCategories[0].slug;
		if (validCategories.length > 1) whereClause.subcategorySlug = validCategories[1].slug;
		if (validCategories.length > 2) whereClause.thirdCategorySlug = validCategories[2].slug;

          whereClause.verified = 1; 
          whereClause.visible = 1; 

		console.log('Searching products with whereClause:', whereClause);

		// Găsim produsele
		const productsByCategory = await db.Products.findAll({
			where: whereClause,
			raw: true,
		});

		console.log('Found products:', productsByCategory.length);

		const returnedData = {
			categoryName: validCategories[0]?.name || '',
			categoryDesc: validCategories[0]?.description || '',
			subcategoryName: validCategories[1]?.name || false,
			subcategoryDesc: validCategories[1]?.description || false,
			thirdCategoryName: validCategories[2]?.name || false,
			thirdCategoryDesc: validCategories[2]?.description || false,
			productsData: productsByCategory.length > 0 ? productsByCategory : false,
		};

		if (!returnedData.productsData) {
			return res.status(404).json({ productsData: false });
		}

		return res.status(200).json(returnedData);
	} catch (error) {
		console.error("API error [category]:", error);
		return res.status(500).json({ error: "Internal server error" });
	}
}