const { Op } = require("sequelize");
const { FeaturedProperty, Property, User } = require("../../models");
const moment = require("moment");

const checkFeaturedPropertiesExpiry = async () => {
  try {
    let featuredProperties = await FeaturedProperty.findAll({
      where: {
        expiresIn: {
          [Op.lt]: moment().format("YYYY-MM-DD"),
        },
      },
    });
    let properties = await Property.findAll({
      where: {
        featured: 1,
      },
    });
    let propertiesArr = properties?.map((e) => e.id) || [];
    featuredProperties = featuredProperties.filter((e) =>
      propertiesArr.includes(e.propertyId)
    );
    if (featuredProperties.length) {
      let featuredPropertiesArr = featuredProperties.map((e) => e.propertyId);
      await Property.update(
        { featured: 0 },
        {
          where: {
            id: {
              [Op.in]: featuredPropertiesArr,
            },
          },
        }
      );
    }

    return true;
  } catch (err) {
    console.log(err);
  }
};

const checkPlanExpiry = async () => {
  try {
    console.log("Checking plan validity...");
    await User.update(
      { planActivationDate: null },
      {
        where: {
          planActivationDate: {
            [Op.lt]: moment().format("YYYY-MM-DD"),
          },
        },
      }
    );
  } catch (err) {
    console.log(err);
  }
  return true;
};

module.exports = {
  checkFeaturedPropertiesExpiry,
  checkPlanExpiry,
};
