import { db } from "@/helpers/api";
const { Op } = require("sequelize");

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

	try {
		const { q, category, subcategory, thirdcategory, limit = 50, offset = 0 } = req.query;

		if (!q || typeof q !== "string") {
			return res.status(400).json({ error: "Search query is required" });
		}

		const sanitizedQuery = q
			.trim()
			.slice(0, 100) 
			.replace(/[<>{}]/g, ""); 

		if (sanitizedQuery.length < 2) {
			return res.status(400).json({ error: "Search query must be at least 2 characters" });
		}

		const parsedLimit = Math.min(parseInt(limit) || 50, 100); // maxim 100 rezultate
		const parsedOffset = Math.max(parseInt(offset) || 0, 0);

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


		const whereClause = {
			[Op.or]: [
				{ name: { [Op.like]: `%${sanitizedQuery}%` } },
				{ desc: { [Op.like]: `%${sanitizedQuery}%` } },
				{ keywords: { [Op.like]: `%${sanitizedQuery}%` } },
                    { categoryName: { [Op.like]: `%${sanitizedQuery}%` } },
                    { subcategoryName: { [Op.like]: `%${sanitizedQuery}%` } },
                    { thirdCategoryName: { [Op.like]: `%${sanitizedQuery}%` } },
			],
		};

		// Adăugăm filtre de categorie dacă există
		if (category && typeof category === "string") {
			const sanitizedCategory = category.trim().slice(0, 100).replace(/[^a-z0-9-]/gi, "");
			if (sanitizedCategory) {
				whereClause.categorySlug = sanitizedCategory;
			}
		}

		if (subcategory && typeof subcategory === "string") {
			const sanitizedSubcategory = subcategory.trim().slice(0, 100).replace(/[^a-z0-9-]/gi, "");
			if (sanitizedSubcategory) {
				whereClause.subcategorySlug = sanitizedSubcategory;
			}
		}

		if (thirdcategory && typeof thirdcategory === "string") {
			const sanitizedThirdCategory = thirdcategory.trim().slice(0, 100).replace(/[^a-z0-9-]/gi, "");
			if (sanitizedThirdCategory) {
				whereClause.thirdCategorySlug = sanitizedThirdCategory;
			}
		}

		console.log("Search whereClause:", whereClause);

		// Căutare produse
		const products = await db.Products.findAndCountAll({
			where: whereClause,
			limit: parsedLimit,
			offset: parsedOffset,
			raw: true,
			order: [["name", "ASC"]],
		});

		console.log(`Found ${products.count} products for query: "${sanitizedQuery}"`);

		return res.status(200).json({
			query: sanitizedQuery,
			total: products.count,
			limit: parsedLimit,
			offset: parsedOffset,
			products: products.rows,
			hasMore: products.count > parsedOffset + parsedLimit,
		});
	} catch (error) {
		console.error("API error [search]:", error);
		return res.status(500).json({ error: "Internal server error" });
	}
}