const Vouchers = require("../models/Vouchers");
const SellersCompany = require("../models/SellersCompany");
const { Op } = require("sequelize");

exports.voucherService = async (
  voucher_code,
  seller_id,
  product_id = null,
  orderSubTotal = 0
) => {
  const startOfToday = new Date();
  startOfToday.setHours(0, 0, 0, 0);
  const voucher = await Vouchers.findOne({
    where: {
      voucher_code,
      status: true,
      valid_until: {
        [Op.gte]: startOfToday,
      },
    },
  });

  let isValidVoucher = true;
  if (!voucher) {
    isValidVoucher = false;
  }

  if (voucher && voucher.min_amount_requirement != null) {
    const parsedMinAmount = parseFloat(voucher.min_amount_requirement);
    if (!isNaN(parsedMinAmount) && orderSubTotal < parsedMinAmount) {
      isValidVoucher = false;
    }
  }

  if (
    voucher &&
    voucher.seller_voucher &&
    voucher.seller_voucher !== seller_id
  ) {
    isValidVoucher = false;
  }

  if (voucher && voucher.available_to_child && voucher.parent_company_id) {
    const seller = await SellersCompany.findByPk(seller_id);

    if (!seller) {
      isValidVoucher = false;
    }

    if (seller.parent_company !== voucher.parent_company_id) {
      isValidVoucher = false;
    }
  }

  if (voucher && voucher.product_id && product_id !== null) {
    if (voucher.product_id !== product_id) isValidVoucher = false;
  }

  if (
    voucher &&
    (voucher.amount == null || voucher.amount === "") &&
    (voucher.amount_in_percent == null || voucher.amount_in_percent === "")
  ) {
    isValidVoucher = false;
  }

  if (isValidVoucher) {
    return voucher;
  } else {
    return null;
  }
};
