const { Op } = require("sequelize");
const { error, success } = require("../../handlers");
const { Plan, FeaturedProperty, Property } = require("../../models");
const moment = require("moment");

const index = async (req, res) => {
  try {
    let { type = "property" } = req.query;
    let plans = await Plan.findAll({
      where: {
        type: type,
      },
      order: [["id", "desc"]],
    });
    return success(res, {
      msg: "Plan listed successfully!!",
      data: plans,
    });
  } catch (err) {
    return error(res, {
      msg: "Something went wrong!!",
    });
  }
};

const featureProperty = async (req, res) => {
  try {
    let userId = req?.user?.id;
    let { propertyId, planId } = req.body;
    console.log(req.body, "===-=-");
    let property = await Property.findOne({
      where: {
        id: propertyId,
        userId: userId,
      },
    });
    if (!property) {
      return error(res, {
        msg: "Please provide valid propertyId!!",
      });
    }
    let isAlreadyFeatured = await FeaturedProperty.findOne({
      where: {
        propertyId: propertyId,
        expiresIn: {
          [Op.gte]: moment().format("YYYY-MM-DD"),
        },
      },
    });
    if (isAlreadyFeatured) {
      return error(res, {
        msg: "You have already buy plan for this property",
      });
    }
    let plan = await Plan.findByPk(planId);
    if (!plan) {
      return error(res, {
        msg: "Something went wrong!!",
      });
    }
    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,
        },
      }
    );
    return success(res, {
      msg: "Property Featured successfully!!",
    });
  } catch (err) {
    console.log(err);
    return error(res, {
      msg: "Something went wrong!!",
    });
  }
};

module.exports = {
  index,
  featureProperty,
};
