// pages/api/products/[...slug].js
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" });

	const { slug } = req.query; // slug poate fi array sau string

	if (!slug) return res.status(400).json({ error: "Invalid slug" });

	const fullPath = Array.isArray(slug) ? slug.join("/") : slug;
	const lastSegment = Array.isArray(slug) ? slug[slug.length - 1] : slug;

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

		const product = await db.Products.findOne({
			where: {
				url: { [Op.in]: [fullPath, lastSegment] },
			},
			raw: true,
		});

		if (!product) return res.status(404).json({ error: "Product not found" });

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