// 多种数据库连接方式测试脚本
// 尝试不同的用户名和密码组合

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

// 多种数据库配置尝试
const dbConfigs = [
  // 配置1: 无密码
  {
    host: 'localhost',
    port: 3306,
    user: 'wwjcloud',
    password: 'wwjcloud',
    database: 'wwjcloud'
  },
  // 配置2: 密码wwjcloud
  {
    host: 'localhost',
    port: 3306,
    user: 'wwjcloud',
    password: 'wwjcloud',
    database: 'wwjcloud'
  },
  // 配置3: 密码123456
  {
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: '123456',
    database: 'wwjcloud'
  },
  // 配置4: 密码admin
  {
    host: 'localhost',
    port: 3306,
    user: 'root',   
    password: 'admin',
    database: 'wwjcloud'
  },
  // 配置5: 尝试连接MySQL服务器（不指定数据库）
  {
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: '',
    database: ''
  },
  // 配置6: 尝试连接MySQL服务器（不指定数据库）
  {
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: 'wwjcloud',
    database: ''
  }
];

async function testConnection(config, index) {
  let connection;
  try {
    console.log(`\n🔌 尝试配置 ${index + 1}:`);
    console.log(`   用户: ${config.user}`);
    console.log(`   密码: ${config.password || '(无密码)'}`);
    console.log(`   数据库: ${config.database || '(不指定)'}`);
    
    connection = await mysql.createConnection(config);
    console.log(`   ✅ 连接成功！`);
    
    // 如果连接成功，测试数据库操作
    if (config.database) {
      await testDatabaseOperations(connection);
    } else {
      // 不指定数据库时，检查可用的数据库
      const [databases] = await connection.execute('SHOW DATABASES');
      console.log(`   📊 可用数据库: ${databases.map(db => db.Database).join(', ')}`);
      
      // 检查是否存在wwjcloud数据库
      const wwjcloudExists = databases.some(db => db.Database === 'wwjcloud');
      if (wwjcloudExists) {
        console.log(`   🎯 找到wwjcloud数据库！`);
        
        // 切换到wwjcloud数据库
        await connection.execute('USE wwjcloud');
        await testDatabaseOperations(connection);
      } else {
        console.log(`   ❌ 未找到wwjcloud数据库`);
      }
    }
    
    return true; // 连接成功
    
  } catch (error) {
    console.log(`   ❌ 连接失败: ${error.message}`);
    return false; // 连接失败
    
  } finally {
    if (connection) {
      await connection.end();
    }
  }
}

async function testDatabaseOperations(connection) {
  try {
    console.log(`   📊 测试数据库操作...`);
    
    // 测试Admin模块
    await testAdminModule(connection);
    
    // 测试Member模块
    await testMemberModule(connection);
    
    // 测试RBAC模块
    await testRbacModule(connection);
    
    // 测试Auth模块
    await testAuthModule(connection);
    
  } catch (error) {
    console.log(`   ❌ 数据库操作测试失败: ${error.message}`);
  }
}

// 测试Admin模块
async function testAdminModule(connection) {
  try {
    // 检查sys_user表是否存在
    const [tables] = await connection.execute("SHOW TABLES LIKE 'sys_user'");
    if (tables.length > 0) {
      const [users] = await connection.execute('SELECT COUNT(*) as count FROM sys_user WHERE is_del = 0');
      console.log(`     ✅ Admin模块: sys_user表 ${users[0].count} 条记录`);
    } else {
      console.log(`     ⚠️  Admin模块: sys_user表不存在`);
    }
  } catch (error) {
    console.log(`     ❌ Admin模块测试失败: ${error.message}`);
  }
}

// 测试Member模块
async function testMemberModule(connection) {
  try {
    // 检查member表是否存在
    const [tables] = await connection.execute("SHOW TABLES LIKE 'member'");
    if (tables.length > 0) {
      const [members] = await connection.execute('SELECT COUNT(*) as count FROM member WHERE is_del = 0');
      console.log(`     ✅ Member模块: member表 ${members[0].count} 条记录`);
    } else {
      console.log(`     ⚠️  Member模块: member表不存在`);
    }
  } catch (error) {
    console.log(`     ❌ Member模块测试失败: ${error.message}`);
  }
}

// 测试RBAC模块
async function testRbacModule(connection) {
  try {
    // 检查sys_role表是否存在
    const [roleTables] = await connection.execute("SHOW TABLES LIKE 'sys_role'");
    if (roleTables.length > 0) {
      const [roles] = await connection.execute('SELECT COUNT(*) as count FROM sys_role');
      console.log(`     ✅ RBAC模块: sys_role表 ${roles[0].count} 条记录`);
    } else {
      console.log(`     ⚠️  RBAC模块: sys_role表不存在`);
    }
    
    // 检查sys_menu表是否存在
    const [menuTables] = await connection.execute("SHOW TABLES LIKE 'sys_menu'");
    if (menuTables.length > 0) {
      const [menus] = await connection.execute('SELECT COUNT(*) as count FROM sys_menu');
      console.log(`     ✅ RBAC模块: sys_menu表 ${menus[0].count} 条记录`);
    } else {
      console.log(`     ⚠️  RBAC模块: sys_menu表不存在`);
    }
  } catch (error) {
    console.log(`     ❌ RBAC模块测试失败: ${error.message}`);
  }
}

// 测试Auth模块
async function testAuthModule(connection) {
  try {
    // 检查auth_token表是否存在
    const [tables] = await connection.execute("SHOW TABLES LIKE 'auth_token'");
    if (tables.length > 0) {
      const [tokens] = await connection.execute('SELECT COUNT(*) as count FROM auth_token WHERE is_revoked = 0');
      console.log(`     ✅ Auth模块: auth_token表 ${tokens[0].count} 条记录`);
    } else {
      console.log(`     ⚠️  Auth模块: auth_token表不存在`);
    }
  } catch (error) {
    console.log(`     ❌ Auth模块测试失败: ${error.message}`);
  }
}

async function main() {
  console.log('🚀 WWJ Cloud 数据库连接测试');
  console.log('=====================================');
  console.log('尝试多种数据库连接配置...');
  
  let successCount = 0;
  
  for (let i = 0; i < dbConfigs.length; i++) {
    const success = await testConnection(dbConfigs[i], i);
    if (success) {
      successCount++;
      console.log(`\n🎉 配置 ${i + 1} 连接成功！`);
      break; // 找到成功的配置就停止
    }
  }
  
  if (successCount === 0) {
    console.log('\n❌ 所有配置都连接失败！');
    console.log('\n💡 建议检查：');
    console.log('   1. MySQL服务是否启动');
    console.log('   2. 端口3306是否被占用');
    console.log('   3. 用户名密码是否正确');
    console.log('   4. 数据库是否存在');
    console.log('\n🔧 可以尝试：');
    console.log('   - 启动MySQL服务');
    console.log('   - 检查MySQL配置文件');
    console.log('   - 重置root密码');
  } else {
    console.log('\n✅ 数据库连接测试完成！');
  }
}

// 运行测试
main(); 