const UserCart = require("../models/UserCart");
const Products = require("../models/Products");
const SellersCompany = require("../models/SellersCompany");
const HardwareCreditCustomers = require("../models/HardwareCreditCustomers");
const HardwareCreditCustomerPayments = require("../models/HardwareCreditCustomerPayments");
const OrderForm = require("../models/OrderForm");

exports.getHardwareCreditCheckout = async (customerId) => {
  let hardwareCreditLimit = 0;
  let orderFormTotalAmount = 0;
  let hardwareCreditPayments = 0;

  // For Hardware Credit
  const userCartDetail = await UserCart.findAll({
    where: {
      user_id: customerId,
    },
    attributes: [
      "menu_id",
      "quantity",
      "price",
      "has_sub_variation_chosen",
      "product_variation_id",
      "product_sub_variation_id",
    ],
    include: [
      {
        model: Products,
        as: "product",
        include: [{ model: SellersCompany, as: "seller" }],
      },
    ],
  });

  if (userCartDetail.length === 0) {
    return {
      status: false,
      current_bal: 0,
    };
  }
  // For Hardware Credit

  const sellerId = userCartDetail[0]?.product?.seller?.id;
  const hardwareCreditRecord = await HardwareCreditCustomers.findOne({
    where: {
      seller_company_id: sellerId,
      customer_id: customerId,
      status: "Verified",
    },
  });

  if (hardwareCreditRecord) {
    hardwareCreditLimit = parseFloat(hardwareCreditRecord.dataValues.customer_credit_limit);

    const orderForm = await OrderForm.findAll({
      attributes: [[Sequelize.fn("SUM", Sequelize.col("total_amount")), "totalAmount"]],
      where: {
        customer_id: customerId,
        status: {
          [Op.notIn]: ["Cancelled", "Denied"],
        },
        payment_method: "Hardware Credit",
      },
    });

    if (orderForm) orderFormTotalAmount = orderForm[0].dataValues.totalAmount ? orderForm[0].dataValues.totalAmount : 0;

    const _hardwareCreditPayments = await HardwareCreditCustomerPayments.findAll({
      where: {
        customer_id: customerId,
        seller_company_id: sellerId,
        status: "Verified",
      },
      attributes: [[Sequelize.fn("SUM", Sequelize.col("amount_paid")), "total_payment"]],
    });

    if (_hardwareCreditPayments)
      hardwareCreditPayments = _hardwareCreditPayments[0].dataValues.total_payment
        ? _hardwareCreditPayments[0].dataValues.total_payment
        : 0;
  }

  const overallTotal =
    parseFloat(hardwareCreditLimit) - (parseFloat(orderFormTotalAmount) - parseFloat(hardwareCreditPayments));
  return {
    status: overallTotal > 0,
    current_bal: overallTotal,
  };
};
