/**
 * An over simplified mongo provider intended to be used for preparint the test db.
 * For code readability, We won't use the the formbird platform's mongodb provider because it has logic
 * we don't necessarily need for setting up the test db.
 */
const MongoClient = require("mongodb").MongoClient;
let _db = null;

getCollection = async () => {
  if(!_db){
    const TestEnv = require('./test-env');
    const testConfig = TestEnv.testConfig;
    const config = testConfig.dataServices.default;
    const client = await MongoClient.connect(`mongodb://${config.host}:${config.port}`, { useNewUrlParser: true });
    _db = client.db(config.db);
  }
  return _db.collection('documents');
};

findDocuments = async (query, sort, projection) => {
  const collection = await getCollection();
  projection = projection ? projection : {};
  return new Promise(function(resolve, reject) {
    try {
      let cursor = collection.find(query, { projection: projection });
      if (sort) {
        cursor = cursor.sort(sort);
      }
      cursor.toArray(function(err, docs) {
        if (err) {
          reject(err);
        } else {
          resolve(docs);
        }
      });
    } catch (err) {
      reject(err);
    }
  });
};

insertDocuments = async (documents) => {
  const collection = await getCollection();
  await collection.insertMany(documents, { checkKeys: false});
};

module.exports = {

  insertDocuments,

  insert : async (document) => {
    await insertDocuments([document]);
    return document;
  },

  find : findDocuments,

  countDocuments : async (query) => {
    const collection = await getCollection();
    return await collection.find(query).count();
  },

  flushTestDB : async () => {
    logger.info('Flushing mongodb testDB...');
    const col = await getCollection();
    await col.deleteMany({});
  },

  createIndexes : async () => {
    logger.info('Recreating mongodb testDB indexes...');
    const col = await getCollection();
    const indexes = [
      {"documentId": 1},
      {"systemHeader.currentVersion" : 1},
      {"systemHeader.deleted" : 1},
      {"systemHeader.templateId" : 1},
      {"systemHeader.keyIds" : 1},
      {"systemHeader.systemType" : 1},
      {"systemHeader.serverCreatedDate" : 1},
      {"systemHeader.serverUpdatedDate" : 1},
      {"systemHeader.createdDate" : 1},
      {"appTags" : 1},
      {"email" : 1}
    ];
    const promises = [];
    for (const i of indexes) {
      promises.push(col.createIndex(i));
    }
    return Promise.all(promises);
  }

};


