"use strict";

const {
  findSearchRequestsForRealEstate
} = require("../helpers/db/searchRequest");
const { findRealEstatesForSearchRequest } = require("../helpers/db/realEstate");
const { addMatches } = require("../helpers/db/searchRequestMatch");
const { MAX_REAL_ESTATES_IN_FIRST_EMAIL } = require("../config/appConfig");
const { EMAIL_FREQUENCY } = require("../common/enums");

const matchRealEstates = async realEstates => {
  if (Array.isArray(realEstates)) {
    const asyncMatchActions = [];
    const matches = {};
    const matchingRecords = [];
    for (const realEstate of realEstates) {
      const searchRequestsPromise = findSearchRequestsForRealEstate(realEstate);
      asyncMatchActions.push(searchRequestsPromise);

      searchRequestsPromise.then(searchRequests => {
        for (const searchRequest of searchRequests) {
          const { id, emailFrequency } = searchRequest;
          if (!matches[id]) {
            matches[id] = {
              searchRequest,
              realEstates: [],
              notifyNow: emailFrequency === EMAIL_FREQUENCY.ASAP.stringId
            };
          }
          matches[id].realEstates.push(realEstate);
          matchingRecords.push({
            searchRequestId: searchRequest.id,
            realEstateId: realEstate.id,
            notified: emailFrequency === EMAIL_FREQUENCY.ASAP.stringId
          });
        }
      });
    }

    await Promise.all(asyncMatchActions);

    await addMatches(matchingRecords);
    return matches;
  }
};

const matchSearchRequest = async searchRequest => {
  const { id: searchRequestId } = searchRequest;

  const realEstates = await findRealEstatesForSearchRequest(
    searchRequest,
    MAX_REAL_ESTATES_IN_FIRST_EMAIL
  );
  const matches = {
    [searchRequestId]: {
      searchRequest,
      realEstates: []
    }
  };
  const matchingRecords = [];

  for (const realEstate of realEstates) {
    matches[searchRequestId].realEstates.push(realEstate);
    matchingRecords.push({
      searchRequestId,
      realEstateId: realEstate.id,
      notified: true
    });
  }

  await addMatches(matchingRecords);
  return matches;
};

module.exports = {
  matchRealEstates,
  matchSearchRequest
};
