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

const MONGODB_URL = process.env.MONGODB_URL || 'mongodb://135.181.103.182:1200/recon_db';

// MongoDB connection options
const options = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    serverSelectionTimeoutMS: 5000, // Timeout after 5s
    socketTimeoutMS: 45000, // Close sockets after 45s of inactivity
    family: 4 // Use IPv4, skip trying IPv6
};

const connectDB = async () => {
    try {
        const connection = await mongoose.connect(MONGODB_URL, options);
        console.log('✅ MongoDB Connected Successfully!');
        console.log(`📦 Database: ${connection.connection.name}`);
        console.log(`🖥️  Host: ${connection.connection.host}`);

        // Handle connection events
        mongoose.connection.on('connected', () => {
            console.log('🔄 Mongoose connected to MongoDB');
        });

        mongoose.connection.on('error', (err) => {
            console.error('❌ Mongoose connection error:', err);
        });

        mongoose.connection.on('disconnected', () => {
            console.log('🔌 Mongoose disconnected from MongoDB');
        });

        // Handle application termination
        process.on('SIGINT', async () => {
            await mongoose.connection.close();
            console.log('MongoDB connection closed through app termination');
            process.exit(0);
        });

        return connection;

    } catch (error) {
        console.error('❌ MongoDB Connection Error:', error.message);
        
        // Provide more detailed error information
        if (error.name === 'MongoServerSelectionError') {
            console.log('\n🔍 Connection Troubleshooting:');
            console.log('1. Check if MongoDB server is running');
            console.log('2. Verify MongoDB URL:', MONGODB_URL);
            console.log('3. Check network connectivity');
            console.log('4. Ensure port 1200 is not blocked by firewall');
            console.log('5. Verify IP address is correct');
        }
        
        // Exit process with failure
        process.exit(1);
    }
};

module.exports = connectDB;
