const mysql = require('mysql2/promise');

async function createSuperAdminTestUser() {
  try {
    const connection = await mysql.createConnection({
      host: 'localhost',
      user: 'root',
      password: '',
      database: 'cms_db'
    });

    console.log('🔧 Creating/Updating Super Admin Test User...');
    
    // Check if Super Admin user exists
    const [existingUsers] = await connection.execute('SELECT * FROM users WHERE role_id = 1 LIMIT 1');
    
    if (existingUsers.length > 0) {
      const user = existingUsers[0];
      console.log('✅ Super Admin user exists:', {
        id: user.id,
        name: user.name,
        email: user.email,
        role_id: user.role_id,
        is_active: user.is_active
      });
      
      // Update password to ensure it's correct
      const bcrypt = require('bcryptjs');
      const hashedPassword = await bcrypt.hash('admin123', 10);
      
      await connection.execute(
        'UPDATE users SET password = ?, is_active = 1 WHERE id = ?',
        [hashedPassword, user.id]
      );
      
      console.log('✅ Password updated to: admin123');
      console.log('✅ User activated');
      
    } else {
      console.log('❌ No Super Admin user found');
    }

    // Verify Super Admin permissions
    const [permissions] = await connection.execute(`
      SELECT COUNT(*) as total 
      FROM role_permissions rp 
      JOIN permissions p ON rp.permission_id = p.id 
      WHERE rp.role_id = 1
    `);
    
    console.log(`✅ Super Admin has ${permissions[0].total} permissions`);

    // Check specific critical permissions
    const criticalPerms = [
      'dashboard.view',
      'settings.access',
      'admin.access',
      'user.read',
      'user.manage_roles'
    ];
    
    console.log('\n🎯 Critical Permissions Check:');
    for (const perm of criticalPerms) {
      const [result] = await connection.execute(`
        SELECT p.name 
        FROM permissions p
        JOIN role_permissions rp ON p.id = rp.permission_id
        WHERE rp.role_id = 1 AND p.name = ?
      `, [perm]);
      console.log(`${result.length > 0 ? '✅' : '❌'} ${perm}`);
    }

    await connection.end();
  } catch (error) {
    console.error('❌ Error:', error.message);
  }
}

createSuperAdminTestUser();
