const { currentSearchRequest } = require("../helpers/url");
const { isValidEmail } = require("../helpers/email");
const {
  notifyForNewSearchRequest
} = require("../services/notificationService");
const { AD_CATEGORY, AD_TYPE, EMAIL_FREQUENCY } = require("../common/enums");

const getQueryReviewTableData = searchRequest => {
  const {
    id,
    adType,
    realEstateType,
    sizeMin,
    sizeMax,
    gardenSizeMin,
    gardenSizeMax,
    priceMin,
    priceMax
  } = searchRequest.dataValues;

  const realEstateTypeObject = AD_CATEGORY[realEstateType];
  const enableGardenSizeEdit = realEstateTypeObject
    ? realEstateTypeObject.hasGardenSize
    : false;

  let adTypeTitle = "";
  switch (adType) {
    case AD_TYPE.AD_TYPE_SALE.stringId:
      adTypeTitle = AD_TYPE.AD_TYPE_SALE.title;
      break;
    case AD_TYPE.AD_TYPE_RENT.stringId:
      adTypeTitle = AD_TYPE.AD_TYPE_RENT.title;
      break;
    default:
      adTypeTitle = "-";
      break;
  }

  const realEstateTypeTitle = realEstateTypeObject
    ? `[${adTypeTitle}] ${realEstateTypeObject.title}`
    : "-";

  const locationTitle = "Promjenite lokaciju";
  const sizeTitle = `${sizeMin} - ${sizeMax} m2`;
  const gardenSizeTitle = enableGardenSizeEdit
    ? `${gardenSizeMin} - ${gardenSizeMax} m2`
    : "-";
  const priceTitle = `${priceMin} - ${priceMax} KM`;

  return [
    {
      id: "realEstateType",
      title: realEstateTypeTitle,
      url: `/vrstanekretnine/${id}?nextStep=filteri`
    },
    {
      id: "location",
      title: locationTitle,
      url: `/lokacija/${id}?nextStep=pregled`
    },
    {
      id: "size",
      title: sizeTitle,
      url: `/filteri/${id}?nextStep=pregled`
    },
    {
      id: "gardenSize",
      title: gardenSizeTitle,
      url: enableGardenSizeEdit ? `/filteri/${id}?nextStep=pregled` : ""
    },
    {
      id: "price",
      title: priceTitle,
      url: `/filteri/${id}?nextStep=pregled`
    }
  ].filter(data => data.title != "-");
};

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

  if (!searchRequest || !searchRequest.dataValues) {
    res.render("notFound", { title: " " });
    return;
  }

  const title = "Da li je ovo to što ste tražili ?";
  const nextStep = req.query.nextStep;
  const error = req.query.error;
  const queryReviewTableData = getQueryReviewTableData(searchRequest);
  const email = searchRequest.email;
  let selectedEmailFrequency;
  switch (searchRequest.emailFrequency) {
    case EMAIL_FREQUENCY.ASAP.stringId:
      selectedEmailFrequency = EMAIL_FREQUENCY.ASAP.id;
      break;
    case EMAIL_FREQUENCY.DAILY.stringId:
      selectedEmailFrequency = EMAIL_FREQUENCY.DAILY.id;
      break;
  }

  res.render("queryReview", {
    nextStep,
    queryReviewTableData,
    title,
    email,
    selectedEmailFrequency,
    error,
    EMAIL_FREQUENCY
  });
};

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

  if (!searchRequest || !searchRequest.dataValues) {
    return null;
  }

  const nextStep = req.query.nextStep || "/ponovo";
  const emailFrequency =
    parseInt(req.body.emailFrequency) || EMAIL_FREQUENCY.ASAP.id;
  const emailInput = req.body.email;
  const emailConfirmInput = req.body.confirmEmail;
  const title = "Da li je ovo to što ste tražili ?";
  const queryReviewTableData = getQueryReviewTableData(searchRequest);

  let emailFrequencyStringId = EMAIL_FREQUENCY.ASAP.stringId;
  if (emailFrequency === EMAIL_FREQUENCY.DAILY.id) {
    emailFrequencyStringId = EMAIL_FREQUENCY.DAILY.stringId;
  }

  searchRequest.emailFrequency = emailFrequencyStringId;

  if (emailInput !== emailConfirmInput) {
    const error = "Greška ! Unešeni emailovi nisu isti";
    res.render("queryReview", {
      error,
      title,
      queryReviewTableData,
      email: ""
    });
    return;
  }

  if (!isValidEmail(emailInput)) {
    const error = "Greška ! Unesite validan email";
    res.render("queryReview", {
      error,
      title,
      queryReviewTableData,
      email: ""
    });
    return;
  }

  searchRequest.email = emailInput;
  searchRequest.subscribed = true;

  try {
    await searchRequest.save();
  } catch (e) {
    console.log("[ERROR] Failed to save search request !", e);
    console.log("Search request : ", searchRequest);
    const error =
      "Greška ! Nismo uspjeli kreirati zahtjev za Vašu pretragu. Molimo pokuštajte ponovo";
    res.render("queryReview", {
      error,
      title,
      queryReviewTableData,
      email: ""
    });
    return;
  }

  try {
    await notifyForNewSearchRequest(searchRequest);
  } catch (e) {
    console.log("[ERROR] Failed to send initial welcome email", e);
    console.log("Search request : ", searchRequest);

    const error =
      "Greška ! Nismo uspjeli poslati email na Vašu adresu, pokušajte sa drugom email adresom";
    res.render("queryReview", {
      error,
      title,
      queryReviewTableData,
      email: ""
    });
    return;
  }

  res.redirect(nextStep);
};

module.exports = {
  getQueryReview,
  postQueryReview
};
