// Fix admin user email
const database = require('./server/config/database');
const bcrypt = require('bcryptjs');

async function fixAdminUser() {
  try {
    await database.initialize();
    
    // Check current admin users
    const admins = await database.all("SELECT id, email, role FROM users WHERE role='admin'");
    console.log('\n📋 Current Admin Users:');
    console.log(admins);
    
    // Check if admin@ashtransfer.com exists
    const correctAdmin = await database.get("SELECT * FROM users WHERE email='admin@ashtransfer.com'");
    
    if (correctAdmin) {
      console.log('\n✅ admin@ashtransfer.com already exists!');
    } else {
      console.log('\n⚠️  admin@ashtransfer.com not found. Creating...');
      
      // Check if info@ashtransfer.com exists
      const oldAdmin = await database.get("SELECT * FROM users WHERE email='info@ashtransfer.com'");
      
      if (oldAdmin) {
        console.log('📝 Updating info@ashtransfer.com → admin@ashtransfer.com');
        await database.run(
          "UPDATE users SET email='admin@ashtransfer.com' WHERE email='info@ashtransfer.com'"
        );
      } else {
        console.log('📝 Creating new admin user...');
        const hashedPassword = await bcrypt.hash('Global2026@', 10);
        await database.run(
          `INSERT INTO users (email, password, first_name, last_name, phone, role, is_verified) 
           VALUES (?, ?, ?, ?, ?, ?, ?)`,
          ['admin@ashtransfer.com', hashedPassword, 'Admin', 'User', '+44 7860 261578', 'admin', 1]
        );
      }
    }
    
    // Update password to ensure it's correct
    console.log('\n🔐 Updating password...');
    const hashedPassword = await bcrypt.hash('Global2026@', 10);
    await database.run(
      "UPDATE users SET password=? WHERE email='admin@ashtransfer.com'",
      [hashedPassword]
    );
    
    // Verify final state
    const finalAdmin = await database.get("SELECT id, email, first_name, last_name, role FROM users WHERE email='admin@ashtransfer.com'");
    console.log('\n✅ Final Admin User:');
    console.log(finalAdmin);
    
    console.log('\n🎉 Admin user fixed!');
    console.log('📧 Email: admin@ashtransfer.com');
    console.log('🔑 Password: Global2026@');
    
    await database.close();
    process.exit(0);
  } catch (error) {
    console.error('❌ Error:', error);
    process.exit(1);
  }
}

fixAdminUser();
