import mongoose from 'mongoose';

export const connectDatabase = async (): Promise<void> => {
  try {
    const { ENV } = await import('./env');
    const mongoUri = ENV.MONGODB_URI;
    
    if (!mongoUri) {
      console.error('❌ MONGODB_URI not found in environment variables!');
      console.error('Please set MONGODB_URI in your .env file');
      process.exit(1);
    }
    
    // Hide password in connection string for logging
    const safeUri = mongoUri.includes('@') 
      ? mongoUri.replace(/\/\/([^:]+):([^@]+)@/, '//$1:***@')
      : mongoUri;
    
    console.log('📡 Connecting to MongoDB:', safeUri);
    
    await mongoose.connect(mongoUri);
    
    console.log('✅ MongoDB connected successfully');
    console.log(`   Database: ${mongoose.connection.name}`);
    console.log(`   Host: ${mongoose.connection.host}:${mongoose.connection.port}`);
  } catch (error: any) {
    console.error('❌ MongoDB connection error:', error.message);
    if (error.message.includes('authentication')) {
      console.error('\n   Authentication failed. Please check:');
      console.error('   1. Username and password are correct');
      console.error('   2. authSource database exists and user has access');
      console.error('   3. Password contains special characters - they should be URL encoded in MONGODB_URI');
      console.error('      Example: @ = %40, : = %3A, / = %2F\n');
    }
    process.exit(1);
  }
};

export const disconnectDatabase = async (): Promise<void> => {
  try {
    await mongoose.disconnect();
    console.log('MongoDB disconnected');
  } catch (error) {
    console.error('Error disconnecting MongoDB:', error);
  }
};
