const axios = require('axios');
const jwt = require('jsonwebtoken');

async function testFrontendAuth() {
  const baseURL = 'http://localhost:3000';
  
  try {
    console.log('=== 测试前端认证流程 ===');
    
    // 1. 模拟前端登录
    console.log('\n1. 模拟前端登录...');
    const loginResponse = await axios.post(`${baseURL}/api/auth/login`, {
      username: 'admin',
      password: '123456'
    });
    
    if (loginResponse.data.status === 'success' || loginResponse.data.success) {
      console.log('✅ 登录成功');
      const token = loginResponse.data.data.token;
      console.log(`Token: ${token.substring(0, 50)}...`);
      
      // 2. 解码token查看内容
      console.log('\n2. 解码JWT Token:');
      try {
        const jwtSecret = 'insurance_super_secret_jwt_key_2024';
        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(`\n权限检查:`);
        console.log(`- 是否有data:read权限: ${hasDataRead}`);
        console.log(`- 权限数组长度: ${Array.isArray(decoded.permissions) ? decoded.permissions.length : 'N/A'}`);
        
      } catch (error) {
        console.error('❌ Token解码失败:', error.message);
      }
      
      // 3. 测试数据仓库接口
      console.log('\n3. 测试数据仓库接口访问:');
      try {
        const overviewResponse = await axios.get(`${baseURL}/api/data-warehouse/overview`, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });
        
        console.log('✅ 数据仓库接口访问成功');
        console.log('响应状态:', overviewResponse.status);
        console.log('响应数据:', JSON.stringify(overviewResponse.data, null, 2));
        
      } catch (error) {
        console.error('❌ 数据仓库接口访问失败:');
        console.error('状态码:', error.response?.status);
        console.error('错误信息:', error.response?.data);
        console.error('完整错误:', error.message);
      }
      
    } else {
      console.error('❌ 登录失败:', loginResponse.data);
    }
    
  } catch (error) {
    console.error('❌ 测试过程中出错:', error.message);
    if (error.response) {
      console.error('响应状态:', error.response.status);
      console.error('响应数据:', error.response.data);
    }
  }
}

testFrontendAuth();