// /pages/api/netopia/create-order.js
import { db } from "@/helpers/api";
import crypto from "crypto";

export default async function handler(req, res) {
	// Inițializare DB
	if (!db.initialized) {
		await db.initialize();
	}

	try {
		switch (req.method) {
			case "POST":
				return await createOrder(req, res);

			case "PUT":
				return await updateOrder(req, res);

			default:
				res.setHeader("Allow", ["POST", "PUT"]);
				return res.status(405).json({
					error: `Method ${req.method} not allowed`,
				});
		}
	} catch (err) {
		console.error("API Error:", err);
		return res.status(500).json({
			error: "Server error",
			message: err.message,
		});
	}
}

async function updateOrder(req, res) {
	if (!db.initialized) await db.initialize();

	try {
		const { orderId, ntpID, status } = req.body;

		if (!orderId) {
			return res.status(400).json({ error: "Order ID is required" });
		}

		// Găsim comanda
		const order = await db.Orders.findByPk(orderId);

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

		// Mapăm statusurile Netopia
		let orderStatus = "pending";

		if (status === 3) {
			orderStatus = "paid";
		} else if (status === 2) {
			orderStatus = "pending";
		} else if (status === 6 || status === 7) {
			orderStatus = "cancelled";
		}

		// Actualizăm comanda
		await order.update({
			netopia_ntpID: ntpID || order.netopia_ntpID,
			status: orderStatus,
		});

		console.log(`✅ Order #${orderId} updated: status=${orderStatus}, ntpID=${ntpID}`);

		return res.status(200).json({
			success: true,
			orderId: order.id,
			status: orderStatus,
		});
	} catch (error) {
		console.error("💥 Update order error:", error);
		return res.status(500).json({
			error: "Eroare server",
			message: error.message,
		});
	}
}

async function createOrder(req, res) {
	const userID = req.userID;
	if (!db.initialized) await db.initialize();

	try {
		const { orderData, cartProducts, cartTotal, billingType, paymentMethod } = req.body;

		// Validare date
		if (!orderData || !cartProducts || !cartTotal) {
			return res.status(400).json({ error: "Date incomplete" });
		}

		// Generăm un orderID unique
		const orderID = `ORD-${crypto.randomBytes(3).toString("hex").toUpperCase()}`;

		// Salvăm comanda în baza de date cu status "pending"
		const orderRecord = await db.Orders.create({
			billingType: billingType ? 1 : 0,

			// Persoană fizică
			pf_prenume: !billingType ? orderData["first-name"] : "",
			pf_nume_familie: !billingType ? orderData["last-name"] : "",
			pf_tara: !billingType ? orderData.country : "",
			pf_judet_oras: !billingType ? orderData.city : "",
			pf_adresa: !billingType ? orderData.address : "",
			pf_numar_telefon: !billingType ? orderData.phone : "",
			pf_email: !billingType ? orderData.email : "",
			pf_mentiuni: !billingType ? orderData.note : "",

			// Persoană juridică
			pj_nume_firma: billingType ? orderData["nume-firma"] : "",
			pj_cui: billingType ? orderData.cui : "",
			pj_nr_reg: billingType ? orderData["nr-inregistrare"] : "",
			pj_banca: billingType ? orderData.banca : "",
			pj_iban: billingType ? orderData.iban : "",
			pj_judet: billingType ? orderData.judet : "",
			pj_localitate: billingType ? orderData.localitate : "",
			pj_adresa: billingType ? orderData.adresa_firma : "",
			pj_adresa_livrare: billingType ? orderData.adresa_livrare : "",
			pj_numar_telefon: billingType ? orderData.phone : "",
			pj_email: billingType ? orderData.email : "",
			pj_mentiuni: billingType ? orderData.note : "",

			userID: userID || 0,
			status: paymentMethod === "ramburs" ? "confirmed" : "pending",
			items: cartProducts,
			total_amount: parseFloat(cartTotal),
			currency: "RON",
			netopia_payment_id: orderID,
		});

		console.log(`✅ Order created: #${orderRecord.id} with orderID: ${orderID}`);

		// Pregătim datele pentru frontend să facă request la Netopia
		const email = billingType ? orderData.email : orderData.email;
		const phone = billingType ? orderData.phone : orderData.phone;
		const firstName = billingType ? orderData["nume-firma"] : orderData["first-name"];
		const lastName = billingType ? "" : orderData["last-name"];
		const city = billingType ? orderData.localitate : orderData.city?.split(",")[1]?.trim() || orderData.city;
		const state = billingType ? orderData.judet : orderData.city?.split(",")[0]?.trim() || "";

		// Construim array-ul de produse pentru Netopia
		const products = cartProducts.map((product) => ({
			name: product.name,
			code: product.id.toString(),
			category: product.category || "General",
			price:
				parseFloat(
					product.priceReduced && parseFloat(product.priceReduced) < parseFloat(product.price)
						? product.priceReduced
						: product.price,
				) * product.quantity,
			vat: 19,
		}));

		// Returnăm datele pentru ca frontend-ul să facă request la Netopia
		const baseUrl =
			process.env.NODE_ENV === "production" ? "https://emagyl.ro" : "http://localhost:3000";

		return res.status(200).json({
			success: true,
			orderId: orderRecord.id,
			orderID: orderID,
               paymentMethod: paymentMethod || "card", 
			netopiaPayload: paymentMethod === "ramburs" ? null : {
				config: {
					emailTemplate: "default",
					notifyUrl: `${baseUrl}/api/netopia/webhook`,
					redirectUrl: `${baseUrl}/order-confirmation?orderId=${orderRecord.id}`,
					language: "ro",
				},
				payment: {
					options: {
						installments: 1,
						bonus: 0,
					},
					instrument: {
						type: "card",
						token: "",
					},
					data: {}, // Frontend va completa cu browser data
				},
				order: {
					ntpID: "",
					posSignature: "30HC-YK8T-I6US-9K86-ZWCU",
					dateTime: new Date().toISOString(),
					description: `Comanda #${orderRecord.id}`,
					orderID: orderID,
					amount: parseFloat(cartTotal),
					currency: "RON",
					billing: {
						email: email,
						phone: phone,
						firstName: firstName,
						lastName: lastName,
						city: city,
						country: 642,
						state: state,
						postalCode: "000000",
						details: billingType ? orderData.adresa_firma : orderData.address,
					},
					shipping: {
						email: email,
						phone: phone,
						firstName: firstName,
						lastName: lastName,
						city: city,
						country: 642,
						state: state,
						postalCode: "000000",
						details: billingType ? orderData.adresa_livrare : orderData.address,
					},
					products: products,
					installments: {
						selected: 0,
						available: [0],
					},
				},
			},
			netopiaConfig: {
				apiUrl: "https://secure.mobilpay.ro/pay",
				apiKey: "M1rImYAKUpQlTn0xp3bheLRctjocl-2rL_Tpv27Ypm31yuNuCBwf2S_xRJx5",
			},
		});
	} catch (error) {
		console.error("💥 Create order error:", error);
		return res.status(500).json({
			error: "Eroare server",
			message: error.message,
		});
	}
}
