import { db } from "@/helpers/api";
import { Op } from "sequelize";
import jwt from "jsonwebtoken";

export default async function handler(req, res) {
	console.log("==================== NETOPIA WEBHOOK ====================");
	console.log("Method:", req.method);
	console.log("Headers:", JSON.stringify(req.headers, null, 2));
	console.log("Body:", JSON.stringify(req.body, null, 2));
	console.log("========================================================");

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

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

	try {
		const verificationToken = req.headers["verification-token"];
		
		if (verificationToken) {
			try {
				const decoded = jwt.decode(verificationToken);
				
				console.log("📝 JWT decoded:", decoded);
				
				// Verifică dacă audience-ul conține posSignature-ul nostru
				if (decoded && decoded.aud && !decoded.aud.includes("30HC-YK8T-I6US-9K86-ZWCU")) {
					console.warn("⚠️ JWT audience mismatch");
				}
			} catch (jwtError) {
				console.warn("⚠️ JWT validation warning:", jwtError.message);
			}
		}

		const data = req.method === "POST" ? req.body : req.query;

		let ntpID, orderID, paymentStatus;

		if (data.ntpID || data.orderID) {
			ntpID = data.ntpID;
			orderID = data.order?.orderID;
			paymentStatus = data.status;
		}

		if (data.payment) {
			ntpID = data.payment.ntpID || ntpID;
			orderID = data.order?.orderID || orderID;
			paymentStatus = data.payment.status || paymentStatus;
		}

		if (!ntpID && !orderID) {
			return res.status(200).json({
				error: "Missing ntpID or orderID",
				received: data,
			});
		}

		const order = await db.Orders.findOne({
			where: {
				[Op.or]: [{ netopia_ntpID: parseInt(ntpID) }, { netopia_payment_id: orderID }],
			},
		});

		if (!order) {
			console.error("❌ Order not found for ntpID/orderID:", ntpID, orderID);
			return res.status(200).json({
				error: "Order not found",
				ntpID,
				orderID,
			});
		}

		console.log(`✅ Order found: #${order.id}`);

		let newStatus = "pending";
		const statusInt = parseInt(paymentStatus);

		switch (statusInt) {
			case 3:
				newStatus = "paid";
				console.log("✅ Payment confirmed (status 3)");
				break;
			case 6:
			case 7:
				newStatus = "cancelled";
				console.log("❌ Payment cancelled/declined (status 6/7)");
				break;
			case 1:
			case 2:
				newStatus = "pending";
				console.log("⏳ Payment pending (status 1/2)");
				break;
			default:
				newStatus = "pending";
				console.log("⚠️ Unknown status:", paymentStatus);
		}

		await order.update({
			status: newStatus,
			netopia_ntpID: parseInt(ntpID),
		});

		console.log("✅ Order updated successfully");

          res.status(200).json({
               errorCode: 0
          });

		if (newStatus === "paid") {
			console.log("🔄 Starting background processing...");
			const BASE_URL = process.env.NODE_ENV === "production" ? "https://emagyl.ro" : "http://localhost:3000";

			fetch(`${BASE_URL}/api/netopia/process-order`, {
				method: "POST",
				headers: { "Content-Type": "application/json" },
				body: JSON.stringify({ orderId: order.id }),
			}).catch((error) => {
				console.error("❌ Eroare apel proces background:", error.message);
			});
		}

	} catch (error) {
		console.error("💥 Webhook error:", error);
		return res.status(200).json({
			error: "Server error",
			message: error.message,
		});
	}
}