const { error, success } = require("../../handlers");
const {
  Bookmark,
  Property,
  User,
  Address,
  PropertyFeatures,
  PropertyImages,
} = require("../../models");

const index = async (req, res) => {
  try {
    let bookmarks = await Bookmark.findAll({
      where: {
        userId: req?.user?.id,
      },
      include: [
        {
          model: Property,
          attributes: [
            "id",
            "name",
            "type",
            "status",
            "addressId",
            "price",
            "image",
            "description",
            "furnishing",
            "propertyStatus",
            "payOnAccess",
            "propertyKind",
            "videoLink",
            "propertyExtraFlags",
            "reraNumber",
            "noOfRooms",
            "noOfBathRooms",
            "nearbyFecilities",
            "area",
            "totalFloors",
            "propertyOnFloor",
          ],
          include: [
            {
              model: Address,
            },
            {
              model: PropertyImages,
              attributes: ["propertyId", "id", "path"],
            },
            {
              model: PropertyFeatures,
              attributes: ["key", "value"],
            },
            {
              model: User,
              attributes: ["firstName", "lastName"],
            },
          ],
        },
      ],
    });

    return success(res, {
      msg: "Bookmarked properties listed successfully!!",
      data: bookmarks,
    });
  } catch (err) {
    return error(res, {
      status: false,
      msg: "Something went wrong!!",
      error: err?.message,
    });
  }
};

const bookmarkProperty = async (req, res) => {
  try {
    isCreated = false;
    let payload = req.body;
    payload["userId"] = req?.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!!",
      data: [{ isBookmarked: isCreated }],
    });
  } catch (err) {
    return error(res, {
      status: false,
      msg: "Something went wrong!!",
      error: err?.message,
    });
  }
};

module.exports = {
  index,
  bookmarkProperty,
};
