const { Op } = require("sequelize");
const { error, success } = require("../../handlers");
const { User, Property, Notification } = require("../../models");
const { getReqInformation } = require("../../utils/Common");

const index = async (req, res) => {
  try {
    let user = await User.findOne({
      where: {
        id: req.user?.id,
      },
      attributes: { exclude: ["updatedAt", "password"] },
    });
    user = user.toJSON();
    const unreadNotificationCount = await Notification.count({
          where: {
            [Op.or]: [
              {
                userId: null,
              },
              {
                userId: req.user?.id,
              },
            ],
            status : 0
          },
        });
      user.unreadNotificationCount = unreadNotificationCount;

    return success(res, {
      msg: "User detail listed successfully!!",
      data: [user],
    });
  } catch (err) {
    console.log(err)
    return error(res, {
      msg: "Something went wrong!!",
    });
  }
};

const getPropertyCount = async (req, res) => {
  try {
    let propertyCount = await Property.count({
      where: {
        userId: req.user?.id,
      },
    });
    let featuredPropertyCount = await Property.count({
      where: {
        userId: req.user?.id,
        featured: 1,
      },
    });

    return success(res, {
      msg: "Property count listed successfully!!",
      data: [
        {
          propertyCount,
          featuredPropertyCount,
        },
      ],
    });
  } catch (err) {
    return error(res, {
      msg: "Something went wrong!!",
    });
  }
};

const updateProfile = async (req, res) => {
  try {
    let payload = req.body;
    let user = await User.findOne({
      where: {
        email: payload?.email,
      },
    });
    if (user && user?.id != req?.user?.id) {
      return error(res, {
        msg: "Email already registered. Please login",
      });
    }
    const { baseUrl } = getReqInformation(req);
    if (req.files?.image?.[0]) {
      payload["image"] = baseUrl + "/uploads/" + req.files.image[0].filename;
    }

    if (req.files?.coverImage?.[0]) {
      payload["coverImage"] =
        baseUrl + "/uploads/" + req.files.coverImage[0].filename;
    }
    await User.update(payload, {
      where: {
        id: req?.user?.id,
      },
    });
    return success(res, {
      msg: "Profile updated successfully!!",
      data: [],
    });
  } catch (err) {
    console.log(err);
    return error(res, {
      msg: "Something went wrong!!",
    });
  }
};

module.exports = {
  index,
  updateProfile,
  getPropertyCount,
};
