const { Op } = require("sequelize");
const moment = require("moment");
const { Plan, Property, FeaturedProperty } = require("../../models");
const { getReqInformation, getSettings } = require("../../utils/Common");

const index = async (req, res) => {
  try {
    let user = req.session?.user;
    let userId = user?.id;
    let propertyId = req?.params?.propertyId;
    let property = await Property.findOne({
      where: {
        id: propertyId,
        userId: userId,
      },
    });
    if (!property) {
      req.flash("error", "Selected property is not associated to this user!!");
      return res.redirect("/properties/my-properties");
    }
    const { baseUrl, endPoint } = getReqInformation(req);
    let settings = await getSettings();
    let plans = await Plan.findAll({
      where: {
        type: "property",
      },
      order: [["id", "desc"]],
    });

    return res.render("plan/index.ejs", {
      user,
      settings,
      baseUrl,
      endPoint,
      plans,
      propertyId: propertyId,
    });
  } catch (err) {
    return res.redirect("/");
  }
};

const featureProperty = async (req, res) => {
  try {
    let userId = req.session?.user?.id;
    let { propertyId, planId } = req.params;
    let isAlreadyFeatured = await FeaturedProperty.findOne({
      where: {
        propertyId: propertyId,
        expiresIn: {
          [Op.gte]: moment().format("YYYY-MM-DD"),
        },
      },
    });
    if (isAlreadyFeatured) {
      req.flash("error", "You have already buy plan for this property");
      return res.redirect("/properties/my-properties");
    }
    let plan = await Plan.findByPk(planId);
    if (!plan) {
      req.flash("error", "Something went wrong!!");
      return res.redirect("/plans/" + propertyId);
    }
    let payload = {
      userId,
      propertyId,
      planId,
      amount: plan?.amount,
      expiresIn: moment().add(plan.noOfDays, "days").format("YYYY-MM-DD"),
    };
    await FeaturedProperty.create(payload);
    await Property.update(
      { featured: 1 },
      {
        where: {
          id: propertyId,
        },
      }
    );
    req.flash("success", "Property Featured successfully!!");
    return res.redirect("/properties/my-properties");
  } catch (err) {
    console.log(err);
    return res.redirect("/plans/" + req?.params?.propertyId);
  }
};

module.exports = {
  index,
  featureProperty,
};
