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

export default async function handler(req, res) {
	const { slug } = req.query;

	if (req.method !== "GET") {
		return res.status(405).json({ error: "Method not allowed" });
	}

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

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

		const product = await db.Products.findOne({
			where: { url: slug },
			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]:", error);
		return res.status(500).json({ error: "Internal server error" });
	}
}
