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

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

  let isValidVoucher = true;
  if (!voucher) 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) {
    if (voucher.product_id !== product_id) isValidVoucher = false;
  }

  console.log("---VALID VOUCHER---");
  console.log(isValidVoucher);
  console.log("---VALID VOUCHER---");

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