const mongoose = require('mongoose');
require('dotenv').config();

const connectDB = async () => {
    try {
        const uri = process.env.URI;
        const dbName = process.env.DB_NAME;

        if (!uri || !dbName) {
            throw new Error("MongoDB URI or DB_NAME is missing in .env");
        }

        console.log('Connecting to database...');

        await mongoose.connect(uri, { dbName });

        console.log(`Connected to database: ${dbName}`);
    } catch (err) {
        console.error('Database connection failed:', err.message);
        process.exit(1); // Exit the process on connection failure
    }
};

module.exports = connectDB;