const { success } = require("../../handlers");
const {
  Bookmark,
  Property,
  Address,
  PropertyFeatures,
  User,
} = require("../../models");
const { getSettings, getReqInformation } = require("../../utils/Common");

const index = async (req, res) => {
  try {
    let user = req.session?.user;
    const { baseUrl, endPoint } = getReqInformation(req);
    let settings = await getSettings();
    let userId = req?.session?.user?.id;
    let bookmarks = await Bookmark.findAll({
      where: {
        userId: userId,
      },
      include: [
        {
          model: Property,
          include: [
            {
              model: Address,
            },
            {
              model: PropertyFeatures,
              attributes: ["key", "value"],
            },
            {
              model: User,
              attributes: ["firstName", "lastName"],
            },
          ],
        },
      ],
    });

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

const bookmarkProperty = async (req, res) => {
  try {
    let isCreated = false;
    let payload = req.body;
    if (!payload?.propertyId) {
      return success(res, {
        status: false,
        msg: "Something went wrong!!",
      });
    }
    payload["userId"] = req?.session?.user?.id;
    let bookMark = await Bookmark.findOne({
      where: payload,
    });
    if (bookMark) {
      await bookMark.destroy();
    } else {
      await Bookmark.create(payload);
      isCreated = true;
    }
    return success(res, {
      msg: isCreated
        ? "Property bookmarked successfully"
        : "Property un bookmarked successfully!!",
      isCreated: isCreated,
    });
  } catch (err) {
    return success(res, {
      status: false,
      msg: "Something went wrong!!",
    });
  }
};

module.exports = {
  bookmarkProperty,
  index,
};
