"use strict";
const db = require("../../models/index");
const sequelize = require("sequelize");
const Op = sequelize.Op;
const { CHECK_UP_DAYS } = require("../../config/appConfig");

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 findAllRequestsForCheckUp = async () => {
  //First we find IDs of search request that don't need to be emailed for check up - to EXCLUDE
  //The ones that received notification for real estate CHECK_UP_DAYS days from now
  const date = new Date();
  const checkUpDate = date.getDate() - CHECK_UP_DAYS;
  date.setDate(checkUpDate);
  const dateQuery = {
    createdAt: {
      [Op.gte]: date
    }
  };

  const excludedMatches = await db.SearchRequestMatch.findAll({
    attributes: ["searchRequestId"],
    where: dateQuery,
    order: [["searchRequestId", "ASC"]]
  });

  const excludedRequestsAll = excludedMatches.map(match => {
    return match.dataValues.searchRequestId;
  });
  //Removing duplicate search request id-s for optimization
  const excludedRequests = [...new Set(excludedRequestsAll)];

  const query = {
    subscribed: true,
    id: {
      [Op.notIn]: excludedRequests
    }
  };
  const allRequestsForCheckUp = await db.SearchRequest.findAll({
    where: query
  });

  return allRequestsForCheckUp;
};

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

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