
const pKey = require('../stripeKey');
const stripe = require('stripe')(pKey); 
const Customer = require('../models/customerModel');
const AppError = require('../utils/appError');
const catchAsync = require('../utils/catchAsync');
const Order = require('../controllers/order');
const {config} = require('dotenv');
config();


// exports.getCheckoutSession = catchAsync(
//   async (req, res, next) => {
//     // 1) Get the currently booked tour
//     // const CustomerLoggedIn = await Customer.findById(req.params.customerId);
//     // console.log(tour);


//     // console.log("Syed---->>>", req.body.data);
//     let client = req.body.client || "web";  // web or trade

//     // let distance = req.body.distance;
//     let totalPrice = req.body.totalPrice;
//     let deliveryPrice = req.body.deliverycharges*100
    
//     // console.log("abc====", req.body.role)
//     // console.log('delivery charges:====', deliveryPrice)
//     let display_name;

//     if (deliveryPrice === 0) {
//       display_name = 'Free Delivery';
//     } else {
//       display_name = 'Delivery';
//     }

//     let id = await Order.postNewOrder(req);
//     console.log("SavedSuccess====", id);
//     console.log(req.body);

//     console.log('Url == >> ',process.env.URL);

//     const session = await stripe.checkout.sessions.create({
//       payment_method_types: ['card'],
//       success_url: `${client === "trade" ? process.env.TRADE_URL : process.env.URL}OrderComplete/${id._id}`,
//       cancel_url: `${client === "trade" ? process.env.TRADE_URL : process.env.URL}`,
//       mode: 'payment',


//       line_items: req.body.data.map((comm) => ({
//         price_data: {
//           currency: 'gbp',
//           product_data: {
//             name: comm.subsubcatagory,
//           },
//           // unit_amount: comm.productPrice * 100,
//           unit_amount: client === "trade" ?  Number.parseInt(comm.wholesellerPrice * 100,0) : Number.parseInt(comm.productPrice * 100,0),
//         },
//         quantity: comm.quantity,
//       })),
//       shipping_address_collection: {
//         allowed_countries: ['GB'],
//       },
//       shipping_options: [
//         {
//           shipping_rate_data: {
//             type: 'fixed_amount',
//             fixed_amount: {
//               amount: deliveryPrice,
//               currency: 'gbp',
//             },
//             display_name: display_name,

//           },
//         }
//       ],
//     });

//     let data = {
//       ID: id._id,
//       sessionID: session.id
//     }
//     console.log("Collected Shipping Info:", session.shipping);
//     console.log("session.id:", session.id);
//     let updatedStripeStatus = await Order.updateStripeStatusOrder(data);
//     console.log("abc====", updatedStripeStatus)

//     res.status(200).json({
//       status: 'success',
//       sessionId: session.id,
//       session,
//     });
//   }
// );




exports.getCheckoutSession = catchAsync(async (req, res, next) => {
  try {
    let client = req.body.client || "web";
    let totalPrice = req.body.totalPrice;
    let deliveryPrice = req.body.deliverycharges * 100;

    let display_name = deliveryPrice === 0 ? 'Free Delivery' : 'Delivery';

    let id;
    
    try {
      id = await Order.postNewOrder(req);
      console.log("Saved Order Success: ", id);
    } catch (err) {
      console.error("Error while saving order:", err);
      return res.status(500).json({ status: "fail", message: "Order could not be saved." });
    }

    console.log('URL ==>> ', process.env.URL);
    console.log('Client Type:', client);
    console.log('Delivery Charges:', deliveryPrice);
    console.log('Line Items:', req.body.data);

    let session;
    try {
      session = await stripe.checkout.sessions.create({
        payment_method_types: ['card'],
        success_url: `${client === "trade" ? process.env.TRADE_URL : process.env.URL}OrderComplete/${id._id}`,
        cancel_url: `${client === "trade" ? process.env.TRADE_URL : process.env.URL}`,
        mode: 'payment',

        line_items: req.body.data.map((comm) => ({
          price_data: {
            currency: 'gbp',
            product_data: {
              name: comm.subsubcatagory || "Unnamed Product",
            },
            unit_amount: client === "trade"
              ? parseInt(comm.wholesellerPrice * 100)
              : parseInt(comm.productPrice * 100),
          },
          quantity: comm.quantity || 1,
        })),

        shipping_address_collection: {
          allowed_countries: ['GB'],
        },

        shipping_options: [
          {
            shipping_rate_data: {
              type: 'fixed_amount',
              fixed_amount: {
                amount: deliveryPrice,
                currency: 'gbp',
              },
              display_name: display_name,
            },
          }
        ],
      });

      console.log("Stripe session created:", session.id);

    } catch (err) {
      console.error("Error while creating Stripe session:", err.message);
      return res.status(400).json({ status: "fail", message: err.message });
    }

    try {
      let updateStatus = await Order.updateStripeStatusOrder({
        ID: id._id,
        sessionID: session.id
      });
      console.log("Stripe status updated:", updateStatus);
    } catch (err) {
      console.error("Error updating Stripe status:", err);
      return res.status(500).json({ status: "fail", message: "Failed to update Stripe status." });
    }

    res.status(200).json({
      status: 'success',
      sessionId: session.id,
      session,
    });
  } catch (err) {
    console.error("Unhandled error in getCheckoutSession:", err);
    res.status(500).json({
      status: 'error',
      message: 'An unexpected error occurred.',
    });
  }
});
