const OrderForm = require("../../models/OrderForm");
const OrderFormDetails = require("../../models/OrderFormDetails");
const Vouchers = require("../../models/Vouchers");
const Customers = require("../../models/Customers");
const Product = require("../../models/Products");
const buildCreditService = require("../../helpers/buildcredit");
exports.importOrders = async (req, res, next) => {
  try {
    const { customerId, voucherCode, shippingMethod, jsonData } = req.body;

    const customerPromise = Customers.findByPk(customerId);
    const voucherPromise = Vouchers.findOne({
      where: {
        voucher_code: voucherCode,
      },
    });

    const shippingMethods = ["Standard Shipping", "Pick-up"];

    if (!shippingMethods.includes(shippingMethod))
      return res.status(400).json({ success: false, message: "Invalid Shipping Method" });

    const [customer, voucher] = await Promise.all([customerPromise, voucherPromise]);

    if (!customer) return res.status(400).json({ success: false, message: "Invalid Customer" });

    const buildCredit = await buildCreditService.getBuildCreditBalance(customer.id);

    if (buildCredit && buildCredit.current_bal === 0) {
      return res.status(400).json({ success: false, message: "No Buildcredit found for this Customer" });
    }
    if (voucherCode) {
      if (!voucher) return res.status(400).json({ success: false, message: "Invalid Voucher Code" });
    }

    let successCount = 0;
    let failedCount = 0;
    if (jsonData) {
      const reference_no = "ORD-IM" + Math.random().toString(36).substring(2, 10).toUpperCase();

      const orderForm = await OrderForm.create({
        email: customer.email,
        name: `${customer.first_name} ${customer.last_name}`,
        customer_id: customer.id,
        contact_number: customer.contact_number,
        pickup_date: new Date(),
        encode_date: new Date(),
        reference_no: reference_no,
        status: "Verified",
        payment_method: "Build Credit",
        address: customer.address,
        longitude: customer.longitude,
        latitude: customer.latitude,
        date_created: new Date(),
        delivery_fee: 0,
        shipping_type: shippingMethod,
        voucher_id_used: voucher ? voucher.id : null,
      });

      let cleanedOrderDetail = [];
      let orderTotalAmount = 0;
      let orderTotalQty = 0;
      let seller_id = null;
      const parsedJsonData = JSON.parse(jsonData);
      for (const data of parsedJsonData) {
        const { productID, originalPrice, quantity, totalAmount } = data;
        if (!productID || !originalPrice || !quantity || !totalAmount) {
          failedCount += 1;
          await orderForm.destroy();
          return res.status(400).json({
            success: false,
            message: "Either ProductID / Original Price / Quantity / Total Amount is empty or invalid.",
            details: `PRODUCT ID: ${productID}, ORIG PRICE: ${originalPrice}, QUANTITY: ${quantity}, TOTAL AMOUNT: ${totalAmount}`,
          });
        }

        const parsedPrice = parseFloat(originalPrice);
        const parsedQuantity = parseFloat(quantity);
        const parsedTotalAmount = parseFloat(totalAmount);

        if (
          isNaN(parsedPrice) ||
          parsedPrice <= 0 ||
          isNaN(parsedQuantity) ||
          parsedQuantity <= 0 ||
          isNaN(parsedTotalAmount) ||
          parsedTotalAmount <= 0
        ) {
          failedCount += 1;
          await orderForm.destroy();
          return res.status(400).json({
            success: false,
            message: "Either ProductID / Original Price / Quantity / Total Amount is empty or invalid.",
            details: `PRODUCT ID: ${productID}, PARSED ORIG PRICE: ${parsedPrice}, PARSED QUANTITY: ${parsedQuantity}, PARSED TOTAL AMOUNT: ${parsedTotalAmount}`,
          });
        }

        const product = await Product.findByPk(productID);

        if (!product) {
          failedCount += 1;
          await orderForm.destroy();
          return res.status(400).json({
            success: false,
            message: "Either ProductID / Original Price / Quantity / Total Amount is empty or invalid.",
            details: `PRODUCT ID: ${productID}`,
          });
        }

        cleanedOrderDetail.push({
          order_form_id: orderForm.id,
          product_id: productID,
          quantity: parsedQuantity,
          price: parsedPrice,
          amount: parsedTotalAmount,
        });
        orderTotalQty += parsedQuantity;
        orderTotalAmount += parsedTotalAmount;
        seller_id = product.seller_id;
      }

      if (orderTotalAmount > buildCredit.current_bal) {
        await orderForm.destroy();
        return res.status(400).json({
          success: false,
          message: "Buildcredit Balance for this customer is insufficient",
        });
      }
      const orderDetailPromises = await OrderFormDetails.bulkCreate(cleanedOrderDetail);
      orderForm.subtotal_amount = orderTotalAmount;
      orderForm.total_amount = orderTotalAmount;
      orderForm.total_qty = orderTotalQty;
      orderForm.seller_id = seller_id;
      successCount = cleanedOrderDetail.length;

      await orderForm.save();

      res.status(200).json({
        success: true,
        order: {
          reference_no: orderForm.reference_no,
          total_amount: orderForm.total_amount,
        },
        count: {
          success: successCount,
          failed: failedCount,
        },
      });
    }
  } catch (err) {
    next(err);
  }
};
