// Initialize MongoDB replica set
// This script runs when the MongoDB container starts for the first time

try {
    print('Starting replica set initialization...');
    
    // Wait a bit for MongoDB to be ready
    sleep(1000);
    
    // Initialize replica set
    var config = {
        _id: 'rs0',
        members: [
            {
                _id: 0,
                host: 'localhost:27017'
            }
        ]
    };
    
    var result = rs.initiate(config);
    print('Replica set initiation result:', JSON.stringify(result));
    
    if (result.ok === 1) {
        print('✅ Replica set initialized successfully!');
        
        // Wait for the replica set to be ready
        print('Waiting for replica set to become ready...');
        sleep(3000);
        
        // Check status
        var status = rs.status();
        print('Replica set status:', JSON.stringify(status, null, 2));
        
    } else {
        print('❌ Failed to initialize replica set:', result.errmsg);
    }
    
} catch (error) {
    print('Error during replica set initialization:', error);
}