const mongoose = require('mongoose');
const log = require('loglevel');

const mongodb = async () => {
    try {
        let mongodbURI = 'mongodb://' + process.env.DB_HOST + ':' + process.env.DB_PORT + '/' + process.env.DB_NAME;

        if (process.env.NODE_ENV !== 'production') {
            mongodbURI = mongodbURI + 'dev';
        }

        if (process.env.POS_DEVELOPMENT_MODE == 'true' || process.env.POS_MULTI_TENANT_MODE == 'true') {
            mongodbURI = mongodbURI + '_' + process.env.CLIENT_NAME;

            if (process.env.POS_MULTI_TENANT_ENV) {
                mongodbURI = mongodbURI + '_' + process.env.POS_MULTI_TENANT_ENV;
            }
        }

        const connection = await mongoose.connect(mongodbURI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useCreateIndex: true,
            useFindAndModify: false,
            serverSelectionTimeoutMS: 60000
        });

        global.mongoConnection = connection.connection.db;

    } catch (err) {
        log.error('MongoDB connection error', err.message);
    }
}

module.exports = mongodb;
