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

async function checkUserPermissions() {
  const connection = await mysql.createConnection({
    host: '129.211.213.226',
    port: 9527,
    user: 'root',
    password: 'aiotAiot123!',
    database: 'insurance_data'
  });

  try {
    console.log('=== 检查用户权限和JWT Token ===');
    
    // 1. 查询admin用户信息
    const [adminUsers] = await connection.execute(
      'SELECT * FROM users WHERE username = ?',
      ['admin']
    );
    
    if (adminUsers.length === 0) {
      console.log('❌ Admin用户不存在');
      return;
    }
    
    const adminUser = adminUsers[0];
    console.log('\n1. Admin用户信息:');
    console.log(`- ID: ${adminUser.id}`);
    console.log(`- 用户名: ${adminUser.username}`);
    console.log(`- 角色ID: ${adminUser.role_id}`);
    console.log(`- 状态: ${adminUser.status}`);
    
    // 2. 查询admin角色权限
    const [roles] = await connection.execute(
      'SELECT * FROM roles WHERE id = ?',
      [adminUser.role_id]
    );
    
    if (roles.length === 0) {
      console.log('❌ Admin角色不存在');
      return;
    }
    
    const adminRole = roles[0];
    console.log('\n2. Admin角色信息:');
    console.log(`- 角色名: ${adminRole.name}`);
    console.log(`- 权限类型: ${typeof adminRole.permissions}`);
    console.log(`- 权限内容: ${JSON.stringify(adminRole.permissions, null, 2)}`);
    
    // 3. 模拟JWT token生成
    console.log('\n3. 模拟JWT Token生成:');
    const tokenPayload = {
      id: adminUser.id,
      username: adminUser.username,
      role_id: adminUser.role_id,
      permissions: adminRole.permissions || []
    };
    
    console.log('Token Payload:', JSON.stringify(tokenPayload, null, 2));
    
    // 使用默认密钥生成token（实际应用中应该从环境变量获取）
    const jwtSecret = process.env.JWT_SECRET || 'your_jwt_secret_key';
    const token = jwt.sign(tokenPayload, jwtSecret, { expiresIn: '7d' });
    
    console.log('\n4. 生成的JWT Token:');
    console.log(token);
    
    // 5. 验证token
    console.log('\n5. 验证JWT Token:');
    try {
      const decoded = jwt.verify(token, jwtSecret);
      console.log('解码后的Token:', JSON.stringify(decoded, null, 2));
      
      // 检查权限
      const hasDataRead = decoded.permissions && 
        (Array.isArray(decoded.permissions) ? 
          decoded.permissions.includes('data:read') : 
          decoded.permissions.includes && decoded.permissions.includes('data:read'));
      
      console.log(`\n6. 权限检查结果:`);
      console.log(`- 是否有data:read权限: ${hasDataRead}`);
      console.log(`- 权限数组长度: ${Array.isArray(decoded.permissions) ? decoded.permissions.length : 'N/A'}`);
      
    } catch (error) {
      console.error('Token验证失败:', error.message);
    }
    
  } catch (error) {
    console.error('检查时出错:', error);
  } finally {
    await connection.end();
  }
}

checkUserPermissions();