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

exports.voucherService = async (
  customer_id,
  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.seller_voucher && voucher.available_to_child) {
    const seller = await SellersCompany.findByPk(seller_id);

    if (!seller) {
      isValidVoucher = false;
    }

    if (seller.parent_company !== voucher.seller_voucher) {
      isValidVoucher = false;
    }
    if (voucher.seller_voucher === seller_id) {
      isValidVoucher = true;
    }
  }

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

  if (voucher && voucher.customer_id && voucher.customer_id !== null) {
    if (voucher.customer_id !== customer_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;
  }
};
