const OrderForm = require("../../models/OrderForm");
const OrderFormDetails = require("../../models/OrderFormDetails");
const RpafPayment = require("../../models/RpafPayment");
const Products = require("../../models/Products");

exports.showOrders = (req, res, next) => {
  const { customerId } = req;
  const { paymentMethod = "" } = req.query;

  const filter = paymentMethod.toLowerCase().trim();
  let queryFilter = "";
  switch (filter) {
    case "buildcredit":
      queryFilter = "Build Credit";
      break;
    case "rpaf":
      queryFilter = "RPAF";
      break;
    case "banktransfer":
      queryFilter = "Bank Transfer";
      break;
    case "split":
      queryFilter = "Split";
      break;
    default:
      return res.status(200).json({
        success: false,
        msg: "Invalid filter (RPAF, BuildCredit, BankTransfer, Split)",
      });
      break;
  }

  OrderForm.findAll({
    where: {
      customer_id: customerId,
      payment_method: queryFilter,
    },
    include: [
      {
        model: RpafPayment,
        as: "rpaf_payment",
        required: false,
        attributes: {
          exclude: ["remainBalance"],
        },
      },
    ],
  })
    .then((orders) => {
      const response = orders.map(
        ({ id, reference_no, payment_method, total_amount, encode_date, status, rpaf_due_date, rpaf_payment }) => {
          let sumVerifiedPayments = 0;
          const rpafPayment = rpaf_payment.map(
            ({ id, reference_no, cheque_no, customer_id, order_id, amount_paid, file_attach, status, date }) => {
              if (status === "Verified") {
                sumVerifiedPayments += parseFloat(amount_paid);
              }
              return {
                id,
                reference_no,
                cheque_no,
                customer_id,
                order_reference_no: order_id,
                amount_paid,
                file_attach: `https://buildhub.ph/uploads/rpafpayment/${file_attach}`,
                status,
                date,
              };
            }
          );
          const adjustedTotalAmount = parseFloat(total_amount) - sumVerifiedPayments;
          return {
            id,
            reference_no,
            payment_method,
            total_amount,
            remaining_balance: adjustedTotalAmount,
            encode_date,
            status,
            payment: rpafPayment,
            due_date: rpaf_due_date,
          };
        }
      );
      res.status(200).json({ success: true, response });
    })
    .catch((err) => {
      next(err);
    });
};

exports.cancelOrder = async (req, res, next) => {
  const { customerId } = req;
  const { cancel_reason = "", order_id } = req.body;

  try {
    const orderForm = await OrderForm.findOne({
      where: {
        id: order_id,
        customer_id: customerId,
      },
    });

    if (!orderForm) return res.status(404).json({ success: false, message: "Invalid order id" });

    console.log(orderForm.status);
    if (orderForm.status !== "Pending" || orderForm.status !== "Verified")
      return res.status(400).json({ success: false, message: "Order has been processed already!" });

    const orderFormDetails = await OrderFormDetails.findAll({
      where: {
        order_form_id: order_id,
      },
    });

    if (orderFormDetails.length > 0) {
      for (const orderFormDetail of orderFormDetails) {
        const { product_id, quantity } = orderFormDetail;

        const product = await Products.findOne({
          where: {
            id: product_id,
          },
        });

        if (product) {
          product.stocks += quantity;
          await product.save();
        }
      }
    }

    orderForm.status = "Cancelled";
    orderForm.cancel_reason = cancel_reason;

    await orderForm.save();
    res.status(200).json({ success: true, message: "Order cancelled successfully." });
  } catch (err) {
    next(err);
  }
};
