const { getRealEstateById } = require("../helpers/db/realEstate");
const { AD_STATUS } = require("../common/enums");

const getRedirect = async (req, res) => {
  const id = req.params.id || null;
  let error = false;
  let redirectUrl = undefined;
  let vipAd = undefined;
  if (!id) {
    error = true;
  } else {
    try {
      const realEstate = await getRealEstateById(id);
      if (!realEstate) {
        error = true;
      } else {
        redirectUrl = realEstate.url;
        vipAd = realEstate.adStatus === AD_STATUS.STATUS_VIP;
      }
    } catch (e) {
      error = true;
    }
  }

  if (error) {
    const title = "";
    res.render("notFound", { title });
  } else {
    const title = "Preusmjeravanje";
    res.render("redirect", { title, redirectUrl, vipAd });
  }
};

module.exports = {
  getRedirect
};
