const mongoose = require('mongoose');
const logger = require('../logger/Logger');
import * as dotenv from 'dotenv'

dotenv.config()
const connect = async () => {

    const url = process.env.MONGO_CONNECTION_STRING;
    logger.info("process.env.MONGO_CONNECTION_STRING :::" + process.env.MONGO_CONNECTION_STRING);

    await mongoose.connection.once("open", async () => {
        logger.info("Connected to database");
    });

    await mongoose.connection.on("error", (err : any) => {
        logger.error("Error connecting to database  ", err);
    });

    await mongoose.connect(url, {
        useNewUrlParser: true,
        useFindAndModify: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
    })
}

const disconnect = () => {

    if (!mongoose.connection) {
      return;
    }

    mongoose.disconnect();

    mongoose.once("close", async () => {
        console.log("Diconnected  to database");
    });

};

module.exports = {
    connect,
    disconnect
}
