"use strict";
const db = require("../../models/index");

const findRealEstatesForSearchRequest = async searchRequestId => {
  const query = {
    searchRequestId
  };

  const realEstatesModel = { model: db.RealEstate, as: "realEstates" };
  const order = [[realEstatesModel, "updatedAt", "desc"]];
  const include = [realEstatesModel];

  const matches = await db.SearchRequestMatch.findAll({
    where: query,
    include,
    order
  });

  const matchingRealEstates = [];
  for (const match of matches) {
    matchingRealEstates.push(...match.realEstates);
  }

  return matchingRealEstates;
};

const findNotNotifiedMatches = async () => {
  const query = {
    notified: false
  };

  const searchRequestsModel = { model: db.SearchRequest, as: "searchRequests" };
  const realEstateModel = { model: db.RealEstate, as: "realEstates" };
  const include = [searchRequestsModel, realEstateModel];

  const matchingRecords = await db.SearchRequestMatch.findAll({
    where: query,
    include
  });

  return matchingRecords;
};

const addMatches = async matchingRecords => {
  return await db.SearchRequestMatch.bulkCreate(matchingRecords, {
    ignoreDuplicates: true
  });
};

module.exports = {
  findRealEstatesForSearchRequest,
  addMatches,
  findNotNotifiedMatches
};
