const moment = require("moment");

const { bulkUpsertRealEstates } = require("../../helpers/db/realEstate");

class PostgresSaver {
  connect() {
    //TODO: It seems we never worry about open/close connection with Sequelize ?
    //TODO: Check if postgres is ready
    return true;
  }

  async save(results) {
    const savedRecords = await bulkUpsertRealEstates(results);

    if (Array.isArray(savedRecords)) {
      const newRealEstates = [];
      const existingRealEstates = [];

      for (const savedRecord of savedRecords) {
        const { createdAt, updatedAt } = savedRecord;

        const createdAtMoment = moment.utc(createdAt);
        const updatedAtMoment = moment.utc(updatedAt);

        if (createdAtMoment.isSame(updatedAtMoment, "second")) {
          newRealEstates.push(savedRecord);
        } else {
          existingRealEstates.push(savedRecord);
        }
      }

      return {
        newRecords: newRealEstates,
        existingRecords: existingRealEstates
      };
    } else {
      throw { message: "[POSTGRES] Failed to save records" };
    }
  }

  close() {
    //TODO: It seems we never worry about open/close connection with Sequelize ?
    return true;
  }
}

module.exports = PostgresSaver;
