// 数据库连接测试脚本
// 验证4个核心模块的数据库连接和字段映射

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

// 数据库配置 - 使用wwjcloud用户和数据库
const dbConfig = {
  host: 'localhost',
  port: 3306,
  user: 'wwjcloud',
  password: 'wwjcloud',
  database: 'wwjcloud'
};

async function testDatabaseConnection() {
  let connection;
  
  try {
    console.log('🔌 正在连接数据库...');
    console.log(`📊 数据库: ${dbConfig.database}`);
    console.log(`🌐 主机: ${dbConfig.host}:${dbConfig.port}`);
    
    // 创建连接
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功！');
    
    // 测试查询各个模块的表结构
    await testAdminModule(connection);
    await testMemberModule(connection);
    await testRbacModule(connection);
    await testAuthModule(connection);
    
    console.log('\n🎉 所有模块数据库测试完成！');
    
  } catch (error) {
    console.error('❌ 数据库连接失败:', error.message);
    console.log('\n💡 请检查：');
    console.log('   1. MySQL服务是否启动');
    console.log('   2. 数据库用户名密码是否正确');
    console.log('   3. wwjcloud数据库是否存在');
    console.log('   4. 端口3306是否被占用');
  } finally {
    if (connection) {
      await connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }
}

// 测试Admin模块
async function testAdminModule(connection) {
  console.log('\n📊 测试Admin模块...');
  
  try {
    // 测试sys_user表
    const [users] = await connection.execute('SELECT COUNT(*) as count FROM sys_user WHERE is_del = 0');
    console.log(`  ✅ sys_user表: ${users[0].count} 条记录`);
    
    // 测试sys_user_role表
    const [userRoles] = await connection.execute('SELECT COUNT(*) as count FROM sys_user_role WHERE delete_time = 0');
    console.log(`  ✅ sys_user_role表: ${userRoles[0].count} 条记录`);
    
    // 测试sys_user_log表
    const [userLogs] = await connection.execute('SELECT COUNT(*) as count FROM sys_user_log');
    console.log(`  ✅ sys_user_log表: ${userLogs[0].count} 条记录`);
    
    // 测试字段映射
    const [userFields] = await connection.execute('DESCRIBE sys_user');
    console.log(`  📋 sys_user表字段数量: ${userFields.length}`);
    
    // 显示关键字段
    const keyFields = userFields.map(field => field.Field).filter(field => 
      ['uid', 'username', 'password', 'real_name', 'status', 'is_del'].includes(field)
    );
    console.log(`  🔑 关键字段: ${keyFields.join(', ')}`);
    
  } catch (error) {
    console.error(`  ❌ Admin模块测试失败: ${error.message}`);
  }
}

// 测试Member模块
async function testMemberModule(connection) {
  console.log('\n👥 测试Member模块...');
  
  try {
    // 测试member表
    const [members] = await connection.execute('SELECT COUNT(*) as count FROM member WHERE is_del = 0');
    console.log(`  ✅ member表: ${members[0].count} 条记录`);
    
    // 测试member_address表
    const [addresses] = await connection.execute('SELECT COUNT(*) as count FROM member_address');
    console.log(`  ✅ member_address表: ${addresses[0].count} 条记录`);
    
    // 测试member_level表
    const [levels] = await connection.execute('SELECT COUNT(*) as count FROM member_level');
    console.log(`  ✅ member_level表: ${levels[0].count} 条记录`);
    
    // 测试字段映射
    const [memberFields] = await connection.execute('DESCRIBE member');
    console.log(`  📋 member表字段数量: ${memberFields.length}`);
    
    // 显示关键字段
    const keyFields = memberFields.map(field => field.Field).filter(field => 
      ['member_id', 'username', 'password', 'nickname', 'mobile', 'status', 'is_del'].includes(field)
    );
    console.log(`  🔑 关键字段: ${keyFields.join(', ')}`);
    
  } catch (error) {
    console.error(`  ❌ Member模块测试失败: ${error.message}`);
  }
}

// 测试RBAC模块
async function testRbacModule(connection) {
  console.log('\n🔐 测试RBAC模块...');
  
  try {
    // 测试sys_role表
    const [roles] = await connection.execute('SELECT COUNT(*) as count FROM sys_role');
    console.log(`  ✅ sys_role表: ${roles[0].count} 条记录`);
    
    // 测试sys_menu表
    const [menus] = await connection.execute('SELECT COUNT(*) as count FROM sys_menu');
    console.log(`  ✅ sys_menu表: ${menus[0].count} 条记录`);
    
    // 测试字段映射
    const [roleFields] = await connection.execute('DESCRIBE sys_role');
    console.log(`  📋 sys_role表字段数量: ${roleFields.length}`);
    
    const [menuFields] = await connection.execute('DESCRIBE sys_menu');
    console.log(`  📋 sys_menu表字段数量: ${menuFields.length}`);
    
    // 显示关键字段
    const roleKeyFields = roleFields.map(field => field.Field).filter(field => 
      ['role_id', 'role_name', 'rules', 'status'].includes(field)
    );
    console.log(`  🔑 sys_role关键字段: ${roleKeyFields.join(', ')}`);
    
    const menuKeyFields = menuFields.map(field => field.Field).filter(field => 
      ['id', 'menu_name', 'menu_key', 'parent_key', 'status'].includes(field)
    );
    console.log(`  🔑 sys_menu关键字段: ${menuKeyFields.join(', ')}`);
    
  } catch (error) {
    console.error(`  ❌ RBAC模块测试失败: ${error.message}`);
  }
}

// 测试Auth模块
async function testAuthModule(connection) {
  console.log('\n🔑 测试Auth模块...');
  
  try {
    // 检查auth_token表是否存在
    const [tables] = await connection.execute("SHOW TABLES LIKE 'auth_token'");
    
    if (tables.length > 0) {
      // 测试auth_token表
      const [tokens] = await connection.execute('SELECT COUNT(*) as count FROM auth_token WHERE is_revoked = 0');
      console.log(`  ✅ auth_token表: ${tokens[0].count} 条记录`);
      
      // 测试字段映射
      const [tokenFields] = await connection.execute('DESCRIBE auth_token');
      console.log(`  📋 auth_token表字段数量: ${tokenFields.length}`);
      
      // 显示关键字段
      const keyFields = tokenFields.map(field => field.Field).filter(field => 
        ['id', 'token', 'user_id', 'user_type', 'expires_at'].includes(field)
      );
      console.log(`  🔑 关键字段: ${keyFields.join(', ')}`);
    } else {
      console.log('  ⚠️  auth_token表不存在，需要先运行测试数据脚本');
      console.log('  📝 请运行: sql/test-data.sql 创建表和数据');
    }
    
  } catch (error) {
    console.error(`  ❌ Auth模块测试失败: ${error.message}`);
  }
}

// 运行测试
testDatabaseConnection(); 