const mongoose = require('mongoose');
const Admin = require('../models/Admin');
require('dotenv').config();

// Use the same MongoDB configuration as the main app
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,
    socketTimeoutMS: 45000,
    family: 4 // Use IPv4, skip trying IPv6
};

// Connect to MongoDB
const connectDB = async () => {
    try {
        await mongoose.connect(MONGODB_URL, options);
        console.log('✅ Connected to MongoDB');
        console.log(`📦 Database: ${mongoose.connection.name}`);
        console.log(`🖥️  Host: ${mongoose.connection.host}`);
    } catch (error) {
        console.error('❌ MongoDB connection error:', error);
        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');
        process.exit(1);
    }
};

// Initialize default admin
const initDefaultAdmin = async () => {
    try {
        await connectDB();
        
        console.log('🔧 Initializing default admin...');
        
        // Create default admin using the static method
        const admin = await Admin.createDefaultAdmin();
        
        console.log('✅ Default admin initialized successfully!');
        console.log('📧 Email:', admin.email);
        console.log('👤 Name:', admin.name);
        console.log('🔑 Role:', admin.role);
        console.log('🆔 ID:', admin._id);
        
        process.exit(0);
    } catch (error) {
        console.error('❌ Error initializing admin:', error);
        process.exit(1);
    }
};

// Run the initialization
initDefaultAdmin();
