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

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

const getRealEstateTypes = async (req, res) => {
  const searchRequest = await currentSearchRequest(req);

  const title = "Koju nekretninu tražite?";
  let selectedAdType = AD_TYPE.AD_TYPE_SALE.id;
  if (
    searchRequest &&
    searchRequest.adType &&
    searchRequest.adType === AD_TYPE.AD_TYPE_RENT.stringId
  ) {
    selectedAdType = AD_TYPE.AD_TYPE_RENT.id;
  }
  const realEstateTypes = Object.keys(AD_CATEGORY)
    .map(category => AD_CATEGORY[category])
    .filter(category => category.title);

  res.render("realEstateType", {
    selectedAdType,
    realEstateTypes,
    title,
    AD_TYPE
  });
};

const postRealEstateTypes = async (req, res) => {
  const searchRequest = await currentSearchRequest(req);

  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;

  const validRealEstateTypes = Object.keys(AD_CATEGORY).filter(
    category => !!AD_CATEGORY[category].title
  );

  const selectedRealEstateType = req.body.realEstateType || null;
  if (validRealEstateTypes.indexOf(selectedRealEstateType) === -1) {
    res.render("notFound", { title: " " });
    return;
  }

  const nextStepPage = req.query.nextStep || "lokacija";

  let nextStepUrl = "";
  if (searchRequest && searchRequest.id) {
    nextStepUrl = `/${nextStepPage}/${searchRequest.id}`;
    searchRequest.adType = adTypeStringId;
    searchRequest.realEstateType = selectedRealEstateType;

    await searchRequest.save();
  } else {
    try {
      const newSearchRequest = await createSearchRequest({
        adType: adTypeStringId,
        realEstateType: selectedRealEstateType
      });

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

module.exports = {
  getRealEstateTypes,
  postRealEstateTypes
};
