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

export default apiHandler({
	get: getAvexData,
});

async function getAvexData(req, res) {
	console.log("=== API PROFIT ===");
	console.log("UserID:", req.userID);
	console.log("Query:", req.query);

	const userID = req.userID;

	if (!db.initialized) {
		console.log("DB not initialized. Initializing...");
		await db.initialize();
	}

	try {
		const userData = await db.User.findByPk(userID);
		if (!userData) {
			console.log("User not found:", userID);
			return res.status(404).json({ error: "Unknown!" });
		}

		if (userData.admin < 1) {
			console.log("Access denied for user:", userID);
			return res.status(401).json({ error: "Unauthorized access." });
		}

		const { sku } = req.query;
		if (!sku) {
			console.log("SKU missing in query");
			return res.status(400).json({ error: "SKU lipsă în query." });
		}

		console.log("Fetching AVEX for SKU:", sku);

		const resp = await fetch(`https://api.avex.ro/products/get_product_data/?product_code=${sku}`, {
			method: "GET",
			headers: {
				Accept: "application/json",
				"Content-Type": "application/json",
				Authorization: "Bearer 7cda655e2e29560c68c2a89ecc1f00.42550232PuongdzeqGqUgN1lVYpaxe1Iu",
			},
		});

		const text = await resp.text();
		let data;
		try {
			data = JSON.parse(text);
		} catch {
			console.log("JSON parse error:", text);
			return res.status(500).json({ error: "Răspuns invalid de la AVEX", raw: text });
		}

		if (!resp.ok) {
			console.log("AVEX response error:", resp.status, data);
			return res.status(resp.status).json({
				error: "Eroare de la AVEX",
				status: resp.status,
				data,
			});
		}

		console.log("AVEX success:", data);
		return res.status(200).json(data);
	} catch (error) {
		console.error("Eroare la cerere:", error);
		return res.status(500).json({ error: "Eroare la cerere: " + error.message });
	}
}