const { User } = require("../../models");
const { getReqInformation, getSettings } = require("../../utils/Common");

const index = async (req, res) => {
  let user = req.session?.user;
  let successMessage = req.flash("success")[0];
  let errorMessage = req.flash("error")[0];
  let settings = await getSettings();
  const { baseUrl, endPoint } = getReqInformation(req);
  return res.render("profile/index.ejs", {
    baseUrl,
    endPoint,
    user,
    successMessage,
    errorMessage,
    settings,
  });
};

const updateProfile = async (req, res) => {
  try {
    let payload = req.body;
    const { baseUrl } = getReqInformation(req);
    if (req.file?.path) {
      payload["image"] = baseUrl + "/uploads/" + req.file?.filename;
    }
    await User.update(payload, {
      where: {
        id: req.session?.user?.id,
      },
    });
    req.flash("success", "Profile updated successfully!!");
    return res.redirect("/profile");
  } catch (err) {
    req.flash("error", "Something went wrong!!");
    return res.redirect("/profile");
  }
};

module.exports = {
  index,
  updateProfile,
};
