const axios = require("axios");
const Cart = require("../models/cartModel");
const Order = require("../models/orderModel");
const AppError = require("../utils/appError");
const catchAsync = require("../utils/catchAsync");

exports.initiatePayment = catchAsync(async (req, res, next) => {
  console.log("🚀 [Paymob KSA] Starting Unified Checkout...");

  // ⚠️ HARDCODED KEYS (Keep these for now until it works)
  const secretKey =
    "sau_sk_live_46186700460a1f9e5fedbd537e7fe74b333d945be2f4a49ab0517f6c7fd2814b";
  const publicKey = "sau_pk_live_iWh7FDdQDXsFKqPUZuVphlsNI6u2tim5";
  const integrationId = 21010;

  // 2. Data Validation & Formatting
  const { phoneNumber, street, building, floor, apartment, city } = req.body;

  let cleanPhone = String(phoneNumber).trim();
  if (!cleanPhone.startsWith("+")) {
    cleanPhone = "+966" + cleanPhone; // Simple force to KSA
  }

  // 3. Get Cart
  const cart = await Cart.findOne({ user: req.user.id });
  if (!cart) return next(new AppError("Cart is empty", 400));
  const amountCents = Math.round(cart.totalPrice * 100);

  // 4. Create Pending Order
  const newOrder = await Order.create({
    user: { _id: req.user.id, name: req.user.name, email: req.user.email },
    items: cart.items,
    totalPrice: cart.totalPrice,
    status: "pending",
    paymentStatus: "pending",
  });

  try {
    // 🔴 CRITICAL FIX: Changed URL from 'accept.paymob.com' to 'ksa.paymob.com'
    const response = await axios.post(
      "https://ksa.paymob.com/v1/intention/",
      {
        amount: amountCents,
        currency: "SAR",
        payment_methods: [integrationId],
        special_reference: newOrder._id.toString(),
        billing_data: {
          first_name: req.user.name.split(" ")[0] || "User",
          last_name: req.user.name.split(" ")[1] || "Name",
          phone_number: cleanPhone,
          email: req.user.email,
          country: "SA",
          city: city || "Riyadh",
          state: city || "Riyadh",
          street: street || "Street",
          building: building || "1",
          floor: floor || "1",
          apartment: apartment || "1",
        },
      },
      {
        headers: {
          Authorization: `Token ${secretKey}`,
          "Content-Type": "application/json",
        },
      },
    );

    // 🔴 CRITICAL FIX: Redirect URL must also be KSA
    const redirectUrl = `https://ksa.paymob.com/unifiedcheckout/?publicKey=${publicKey}&clientSecret=${response.data.client_secret}`;

    console.log("✅ [Paymob] Success! URL Generated:", redirectUrl);

    res.status(200).json({
      status: "success",
      url: redirectUrl,
    });
  } catch (err) {
    console.error("❌ [Paymob Request Failed]");
    if (err.response) {
      console.error("👉 Status:", err.response.status);
      console.error("👉 Reason:", JSON.stringify(err.response.data, null, 2));
    } else {
      console.error("👉 Error:", err.message);
    }
    await Order.findByIdAndDelete(newOrder._id);
    return next(new AppError("Payment initiation failed.", 500));
  }
});

// Webhook
exports.paymobWebhook = catchAsync(async (req, res, next) => {
  const { obj } = req.body;
  if (obj && obj.success === true) {
    const orderId = obj.special_reference || obj.order?.merchant_order_id;
    if (orderId) {
      const order = await Order.findById(orderId);
      if (order && order.status !== "completed") {
        order.paymentStatus = "paid";
        order.status = "completed";
        await order.save();
        await Cart.findOneAndDelete({ user: order.user._id });
      }
    }
  }
  res.status(200).send();
});
