require('dotenv').config();
const db = require('../config/database');
const bcrypt = require('bcryptjs');

async function createAdminIfEmpty() {
    const connection = db.promise();
    
    try {
        console.log('🔍 Checking users table...');
        
        // Check if users table has any records
        const [userCount] = await connection.query('SELECT COUNT(*) as count FROM users');
        const count = userCount[0].count;
        
        console.log(`📊 Current users count: ${count}`);
        
        if (count === 0) {
            console.log('📝 Users table is empty. Creating admin user...');
            
            // Hash the password using the same method as signup
            const hashedPassword = await new Promise((resolve, reject) => {
                bcrypt.hash('123456789', 10, (err, hash) => {
                    if (err) reject(err);
                    else resolve(hash);
                });
            });
            
            // Insert admin user
            const [result] = await connection.query(
                `INSERT INTO users 
                    (first_name, last_name, email, phone_number, password, role, is_verified, created_at, updated_at) 
                 VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
                [
                    'Admin',
                    'Admin', 
                    'admin@example.com',
                    '+265880000000',
                    hashedPassword,
                    'admin',
                    true // Admins are pre-verified
                ]
            );
            
            console.log('✅ Admin user created successfully!');
            console.log('\n📐 Admin User Details:');
            console.log('  ID:', result.insertId);
            console.log('  Name: Admin Admin');
            console.log('  Email: admin@example.com');
            console.log('  Phone: +265880000000');
            console.log('  Role: admin');
            console.log('  Verified: Yes');
            console.log('\n🔐 Login Credentials:');
            console.log('  Email: admin@example.com');
            console.log('  Password: 123456789');
            console.log('\n⚠️  Please change the password after first login for security.');
            
        } else {
            console.log('ℹ️  Users table already has records. Skipping admin creation.');
        }
        
    } catch (error) {
        console.error('❌ Error:', error.message);
        if (error.code === 'ER_DUP_ENTRY') {
            console.log('ℹ️  Admin user already exists.');
        }
    } finally {
        await connection.end();
    }
}

// Run the script
createAdminIfEmpty();
