const { createSearchRequest } = require("../helpers/db/searchRequest");

const { AD_TYPE, AD_CATEGORY } = require("../common/enums");

const getWelcome = (req, res) => {
  res.render("welcome", {
    title: false,
    AD_TYPE
  });
};

const postWelcome = async (req, res) => {
  const adType = parseInt(req.body.adType);

  const adTypeStringIds = {
    [AD_TYPE.AD_TYPE_SALE.id]: AD_TYPE.AD_TYPE_SALE.stringId,
    [AD_TYPE.AD_TYPE_RENT.id]: AD_TYPE.AD_TYPE_RENT.stringId
  };

  const adTypeStringId =
    adTypeStringIds[adType] || AD_TYPE.AD_TYPE_SALE.stringId;

  let nextStepUrl = "";
  try {
    const newSearchRequest = await createSearchRequest({
      adType: adTypeStringId,
      realEstateType: AD_CATEGORY.FLAT.id
    });

    nextStepUrl = `/vrstanekretnine/${newSearchRequest.id}`;
  } catch (error) {
    console.log(error);
    nextStepUrl = `/`;
  }

  res.redirect(nextStepUrl);
};

module.exports = {
  getWelcome,
  postWelcome
};
