const axios = require('axios');

// 测试部署环境的nginx配置
const baseURL = 'https://ad.ningmuyun.com';

const testAPIs = [
  // 测试正常工作的接口
  {
    name: '数据览仓接口',
    url: '/api/government/data-center',
    method: 'GET'
  },
  {
    name: '市场行情接口',
    url: '/api/government/market-price',
    method: 'GET'
  },
  {
    name: '行政部门接口',
    url: '/api/government/departments',
    method: 'GET'
  },
  
  // 测试有问题的接口
  {
    name: '行政人员接口',
    url: '/api/government/admin-staff',
    method: 'GET'
  },
  {
    name: '养殖户接口',
    url: '/api/government/farmers',
    method: 'GET'
  },
  {
    name: '智能项圈接口',
    url: '/api/government/collars',
    method: 'GET'
  },
  {
    name: '养殖类型接口',
    url: '/api/government/farm-types',
    method: 'GET'
  },
  {
    name: '养殖种类接口',
    url: '/api/government/animal-types',
    method: 'GET'
  }
];

async function testAPI(api) {
  try {
    console.log(`\n测试 ${api.name}...`);
    console.log(`URL: ${baseURL}${api.url}`);
    
    const response = await axios({
      method: api.method,
      url: `${baseURL}${api.url}`,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    console.log(`✅ 状态码: ${response.status}`);
    console.log(`✅ 响应: ${JSON.stringify(response.data).substring(0, 100)}...`);
    return { success: true, status: response.status, data: response.data };
    
  } catch (error) {
    console.log(`❌ 错误: ${error.message}`);
    if (error.response) {
      console.log(`❌ 状态码: ${error.response.status}`);
      console.log(`❌ 响应: ${JSON.stringify(error.response.data)}`);
      
      // 检查是否是路径重复错误
      if (error.response.data && JSON.stringify(error.response.data).includes('government/government')) {
        console.log(`🚨 发现路径重复错误！`);
        console.log(`   这可能是nginx配置问题导致的路径重复`);
      }
      
      // 检查是否是404错误
      if (error.response.status === 404) {
        console.log(`🚨 404错误 - 接口不存在或路由配置问题`);
      }
      
      // 检查是否是500错误
      if (error.response.status === 500) {
        console.log(`🚨 500错误 - 服务器内部错误`);
      }
    } else if (error.code === 'ECONNREFUSED') {
      console.log(`🚨 连接被拒绝 - 服务可能没有启动`);
    } else if (error.code === 'ENOTFOUND') {
      console.log(`🚨 域名解析失败 - 请检查域名配置`);
    }
    return { success: false, error: error.message, status: error.response?.status };
  }
}

async function runTests() {
  console.log('测试部署环境的nginx配置...');
  console.log('='.repeat(60));
  
  const results = [];
  
  for (const api of testAPIs) {
    const result = await testAPI(api);
    results.push({
      name: api.name,
      url: api.url,
      ...result
    });
    
    // 等待1秒再测试下一个接口
    await new Promise(resolve => setTimeout(resolve, 1000));
  }
  
  console.log('\n' + '='.repeat(60));
  console.log('测试结果汇总:');
  console.log('='.repeat(60));
  
  const successCount = results.filter(r => r.success).length;
  const totalCount = results.length;
  
  results.forEach(result => {
    const status = result.success ? '✅' : '❌';
    console.log(`${status} ${result.name}`);
  });
  
  console.log(`\n总计: ${successCount}/${totalCount} 个接口测试通过`);
  
  if (successCount === totalCount) {
    console.log('🎉 所有接口测试通过！nginx配置正常！');
  } else {
    console.log('⚠️  部分接口测试失败，请检查nginx配置');
    
    // 分析失败原因
    const failedResults = results.filter(r => !r.success);
    const pathDuplicationErrors = failedResults.filter(r => 
      r.error && r.error.includes('government/government')
    );
    
    if (pathDuplicationErrors.length > 0) {
      console.log('\n🔍 问题分析:');
      console.log('🚨 发现路径重复错误，这通常是由以下原因造成的:');
      console.log('   1. nginx配置中有多个location规则匹配同一个请求');
      console.log('   2. proxy_pass配置不正确导致路径重复');
      console.log('   3. 后端服务返回的路径包含重复的路径段');
      console.log('\n💡 建议解决方案:');
      console.log('   1. 检查nginx配置中的location规则顺序');
      console.log('   2. 确保只有一个location规则匹配/api/路径');
      console.log('   3. 检查proxy_pass配置是否正确');
    }
  }
}

// 运行测试
runTests().catch(console.error);
