require("dotenv").config();
const stripe = require("stripe")(process.env.STRIPE_KEY);
const Payment = require("../models/Payment");
const Trader = require("../models/Trader");
const paypal = require("@paypal/checkout-server-sdk");

const environment = new paypal.core.SandboxEnvironment(
  process.env.PAYPAL_CLIENT_ID,
  process.env.PAYPAL_SECRET_KEY
);

const client = new paypal.core.PayPalHttpClient(environment);

// exports.MakePayment = async ( req,res) =>{
//     try{
//         const { paymentMethodId, amount, shipping, products, customerDetails, cardDetails } = req.body;
//         // console.log('Here is body==>>',req.body)
//         if(!paymentMethodId || !amount || shipping===undefined || !products || !customerDetails || !cardDetails){
//             return res.status(400).json({ message:'You must Provide all fields' });
//         }
//         const paymentIntent = await stripe.paymentIntents.create({
//             amount,
//             currency: 'gbp',
//             payment_method: paymentMethodId,
//             confirm:true,
//             automatic_payment_methods: {
//                 enabled: true,
//                 allow_redirects: 'never',
//             },
//         });

//         console.log('payment Intent ==>>',paymentIntent);
//         const payment = new Payment({
//             paymentMethodId,
//             amount,
//             shipping,
//             products,
//             customerDetails,
//             paymentStatus: paymentIntent.status,
//             cardDetails,
//         });
//         await payment.save();
//         return res.json({ success: true, paymentIntent });
//     }catch(error){
//         console.log('Error making payment==>>',error);
//         return res.status(500).json({ error: error.message ,message:'Internal Server Error'});
//     }
// }

exports.createCustomer = async ({ email, name }) => {
  try {
    const customer = await stripe.customers.create({
      email,
      name,
    });
    return customer;
  } catch (error) {
    console.log("Error creating stripe customer", error);
  }
};

exports.MakePayment = async (req, res) => {
  try {
    const {
      paymentMethodId,
      customerId,
      amount,
      shipping,
      products,
      customerDetails,
      cardDetails,
    } = req.body;
    // console.log('Here is body==>>',req.body)
    if (
      !paymentMethodId ||
      !amount ||
      shipping === undefined ||
      !products ||
      !customerDetails ||
      !cardDetails
    ) {
      return res.status(400).json({ message: "You must Provide all fields" });
    }
    const paymentIntent = await stripe.paymentIntents.create({
      amount,
      currency: "gbp",
      payment_method: paymentMethodId,
      customer: customerId,
      confirm: true,
      automatic_payment_methods: {
        enabled: true,
        allow_redirects: "never",
      },
    });

    console.log("payment Intent ==>>", paymentIntent);
    const payment = new Payment({
      paymentMethodId,
      amount,
      shipping,
      products,
      customerDetails,
      paymentStatus: paymentIntent.status,
      cardDetails,
    });
    await payment.save();
    return res.json({ success: true, paymentIntent });
  } catch (error) {
    console.log("Error making payment==>>", error);
    return res
      .status(500)
      .json({ error: error.message, message: "Internal Server Error" });
  }
};

exports.MakeSavedPayment = async (req, res) => {
  try {
    const {
      paymentMethodId,
      customerId,
      amount,
      shipping,
      products,
      customerDetails,
    } = req.body;
    // console.log('Here is body==>>',req.body)
    if (
      !paymentMethodId ||
      !amount ||
      shipping === undefined ||
      !products ||
      !customerDetails
    ) {
      return res.status(400).json({ message: "You must Provide all fields" });
    }
    const paymentIntent = await stripe.paymentIntents.create({
      amount,
      currency: "gbp",
      payment_method: paymentMethodId,
      customer: customerId,
      confirm: true,
      automatic_payment_methods: {
        enabled: true,
        allow_redirects: "never",
      },
    });

    console.log("payment Intent ==>>", paymentIntent);
    const payment = new Payment({
      paymentMethodId,
      amount,
      shipping,
      products,
      customerDetails,
      paymentStatus: paymentIntent.status,
    });
    await payment.save();
    return res.json({ success: true, paymentIntent });
  } catch (error) {
    console.log("Error making payment==>>", error);
    return res
      .status(500)
      .json({ error: error.message, message: "Internal Server Error" });
  }
};

exports.getSavedPaymentMethods = async (req, res) => {
  try {
    const userId = req.params.userId;
    const payments = await Payment.find({ "customerDetails.id": userId });
    res.json({ success: true, payments });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: error.message });
  }
};

exports.savePaymentMethod = async (req, res) => {
  try {
    const { customerId, paymentMethodId } = req.body;
    const paymentMethod = await stripe.paymentMethods.attach(paymentMethodId, {
      customer: customerId,
    });
    await stripe.customers.update(customerId, {
      invoice_settings: {
        default_payment_method: paymentMethodId,
      },
    });
    res.json({ success: true, paymentMethod });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

exports.getSavedPaymentMethods = async (req, res) => {
  try {
    const traderId = req.params.traderId;

    const trader = await Trader.findById(traderId);
    if (!trader.stripeCustomerId) {
      const stripeCustomer = await createCustomer({
        email: trader.email,
        name: trader.firstName,
      });
      trader.stripeCustomerId = stripeCustomer.id;
      await trader.save();
    }
    const customerId = trader.stripeCustomerId;

    const paymentMethods = await stripe.paymentMethods.list({
      customer: customerId,
      type: "card",
    });

    res.json({ success: true, paymentMethods });
  } catch (error) {
    console.log("Error geting payment methods", error);
    res.status(500).json({ error: error.message });
  }
};

exports.registerStripeCustomer = async (req, res) => {
  try {
    const traderId = req.params.traderId;
    const trader = await Trader.findById(traderId);
    if (!trader.stripeCustomerId) {
      const stripeCustomer = await createCustomer({
        email: trader.email,
        name: trader.firstName,
      });
      trader.stripeCustomerId = stripeCustomer.id;
      await trader.save();
    }
    return res.status(200).json({
      success: true,
      message: "The trader has been registered with the stripe successfully.",
    });
  } catch (error) {
    console.log("Error creating stripe customer", error);
    return res.status(500).json({
      success: false,
      message: "Error registering trader with the stripe. Please try again.",
    });
  }
};

// POST: /api/payment/paypal-create-order
exports.createPaypalOrder = async (req, res) => {
  try {
    const { name, email, total } = req.body;

    const orderRequest = new paypal.orders.OrdersCreateRequest();
    orderRequest.prefer("return=representation");
    orderRequest.requestBody({
      intent: "CAPTURE",
      purchase_units: [
        {
          amount: {
            currency_code: "USD",
            value: total.toFixed(2),
          },
          description: `Purchase at our store`,
        },
      ],
      payer: {
        name: {
          given_name: name.split(" ")[0],
          surname: name.split(" ")[1] || "",
        },
        email_address: email,
      },
    });

    const orderResponse = await client.execute(orderRequest);

    if (
      !orderResponse ||
      !orderResponse.result ||
      orderResponse.result.status !== "CREATED"
    ) {
      return res.status(400).json({
        success: false,
        message: "Failed to create PayPal order",
      });
    }

    return res.status(200).json({
      success: true,
      orderId: orderResponse.result.id,
    });
  } catch (error) {
    console.error("Error creating PayPal order:", error);
    return res.status(500).json({
      success: false,
      message: "Internal server error",
    });
  }
};

// POST: /api/payment/paypal-capture
exports.capturePaypalOrder = async (req, res) => {
  try {
    const { orderId, amount, shipping, products, customerDetails } = req.body;

    if (!orderId || !amount || !products || !customerDetails) {
      return res.status(400).json({ message: "You must Provide all fields" });
    }

    // Capture the PayPal order
    const captureRequest = new paypal.orders.OrdersCaptureRequest(orderId);
    captureRequest.requestBody({});
    const captureResponse = await client.execute(captureRequest);

    if (!captureResponse || captureResponse.result.status !== "COMPLETED") {
      return res.status(400).json({
        success: false,
        message: "Payment not completed",
      });
    }

    const payment = new Payment({
      amount,
      shipping,
      products,
      customerDetails,
      paymentStatus: "completed",
    });

    return res.status(200).json({
      success: true,
      message: "Payment and order successfully captured",
      payment: payment,
    });
  } catch (error) {
    console.error("Error capturing PayPal order:", error);
    return res.status(500).json({
      success: false,
      message: "Internal server error",
    });
  }
};
