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

const getSearchRequest = async searchRequestId => {
  try {
    return await db.SearchRequest.findByPk(searchRequestId);
  } catch (error) {
    return null;
  }
};

const createSearchRequest = async (searchRequestFields = {}) => {
  return await db.SearchRequest.create(searchRequestFields);
};

const findSearchRequestsForRealEstate = async realEstate => {
  const {
    price,
    area,
    adType,
    realEstateType,
    locationLat,
    locationLong
  } = realEstate;

  if (!locationLat || !locationLong) {
    return [];
  }

  const stGeometry = sequelize.fn(
    "ST_GEOMFROMTEXT",
    `POINT (${locationLong} ${locationLat})`,
    4326
  );
  const areaToSearchColumn = sequelize.col("areaToSearch");
  const contains = sequelize.fn("ST_Contains", areaToSearchColumn, stGeometry);

  const geoSearchQueryPart = sequelize.where(contains, true);

  const query = {
    adType,
    realEstateType,
    subscribed: true,
    [Op.and]: geoSearchQueryPart
  };

  if (price) {
    query.priceMin = {
      [Op.lte]: price
    };
    query.priceMax = {
      [Op.gte]: price
    };
  }

  if (area) {
    query.sizeMin = {
      [Op.lte]: area
    };
    query.sizeMax = {
      [Op.gte]: area
    };
  }

  return await db.SearchRequest.findAll({ where: query });
};

module.exports = {
  getSearchRequest,
  createSearchRequest,
  findSearchRequestsForRealEstate
};
