const { createSearchRequest } = require("../helpers/db/searchRequest");
const { createRealEstate } = require("../helpers/db/realEstate");
const { createKiviOriginal } = require("../helpers/db/kiviOriginal");
const { AD_TYPE, AD_CATEGORY, AD_AGENCY } = require("../common/enums");
const { APP_URL } = require("../config/appConfig");

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

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

  let nextStepUrl = "";

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

      nextStepUrl = `/vrstanekretnine/${newSearchRequest.id}`;
    } catch (error) {
      console.log(error);
      nextStepUrl = `/`;
    }
  } else if (publishAdType) {
    const adTypeStringId = getAdTypeString(publishAdType);

    try {
      //First we create new Kivi Ad Original object in db then new Real Estate
      //Problem with id-s
      const newKiviOriginal = await createKiviOriginal({
        email: ""
      });
      //Temporary url because we have cyclic id call - need to override for safety measures
      const newKiviAdViewUrl = `${APP_URL}/preglednekretnine/${newKiviOriginal.kiviAdId}`;

      const newRealEstate = await createRealEstate({
        adType: adTypeStringId,
        realEstateType: AD_CATEGORY.FLAT.id,
        url: newKiviAdViewUrl,
        originAgencyName: AD_AGENCY.KIVI,
        agencyObjectId: newKiviOriginal.kiviAdId
      });

      nextStepUrl = `/objavinekretninu/${newKiviOriginal.kiviAdId}`;
    } catch (error) {
      console.log(error);
      nextStepUrl = `/`;
    }
  }

  res.redirect(nextStepUrl);
};

//--- Helper function
const getAdTypeString = 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;

  return adTypeStringId;
};

module.exports = {
  getWelcome,
  postWelcome
};
