/**
 * 险种管理API测试脚本
 * 使用Node.js和axios进行API测试
 */

const axios = require('axios');

// 配置
const BASE_URL = 'http://localhost:3000/api';
const TEST_USER = {
  username: 'admin',
  password: '123456'
};

let authToken = '';
let testInsuranceTypeId = null;

// 创建axios实例
const api = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器 - 添加认证头
api.interceptors.request.use(config => {
  if (authToken) {
    config.headers.Authorization = `Bearer ${authToken}`;
  }
  return config;
});

// 响应拦截器 - 处理错误
api.interceptors.response.use(
  response => response,
  error => {
    console.error('API请求错误:', error.response?.data || error.message);
    return Promise.reject(error);
  }
);

// 测试函数
async function runTests() {
  console.log('🚀 开始险种管理API测试...\n');

  try {
    // 1. 用户登录
    await testLogin();
    
    // 2. 获取险种列表
    await testGetInsuranceTypes();
    
    // 3. 创建险种
    await testCreateInsuranceType();
    
    // 4. 获取单个险种
    await testGetInsuranceTypeById();
    
    // 5. 更新险种
    await testUpdateInsuranceType();
    
    // 6. 更新险种状态
    await testUpdateInsuranceTypeStatus();
    
    // 7. 删除险种
    await testDeleteInsuranceType();
    
    console.log('✅ 所有测试完成！');
    
  } catch (error) {
    console.error('❌ 测试失败:', error.message);
    process.exit(1);
  }
}

// 1. 测试用户登录
async function testLogin() {
  console.log('📝 测试用户登录...');
  
  try {
    const response = await api.post('/auth/login', TEST_USER);
    
    if (response.data.success && response.data.data.token) {
      authToken = response.data.data.token;
      console.log('✅ 登录成功');
    } else {
      throw new Error('登录失败：未获取到token');
    }
  } catch (error) {
    throw new Error(`登录失败: ${error.response?.data?.message || error.message}`);
  }
  
  console.log('');
}

// 2. 测试获取险种列表
async function testGetInsuranceTypes() {
  console.log('📋 测试获取险种列表...');
  
  try {
    const response = await api.get('/insurance-types', {
      params: {
        page: 1,
        pageSize: 10,
        status: 'active'
      }
    });
    
    if (response.data.success) {
      console.log(`✅ 获取险种列表成功，共 ${response.data.pagination.total} 条记录`);
      console.log(`   当前页: ${response.data.pagination.page}/${response.data.pagination.totalPages}`);
    } else {
      throw new Error('获取险种列表失败');
    }
  } catch (error) {
    throw new Error(`获取险种列表失败: ${error.response?.data?.message || error.message}`);
  }
  
  console.log('');
}

// 3. 测试创建险种
async function testCreateInsuranceType() {
  console.log('➕ 测试创建险种...');
  
  const testData = {
    name: `测试险种_${Date.now()}`,
    description: '这是一个测试用的险种',
    applicable_livestock: '牛',
    insurance_term: '1年',
    policy_form: '团体保险',
    coverage_amount_min: 1000.00,
    coverage_amount_max: 50000.00,
    premium_rate: 0.05
  };
  
  try {
    const response = await api.post('/insurance-types', testData);
    
    if (response.data.success && response.data.data.id) {
      testInsuranceTypeId = response.data.data.id;
      console.log(`✅ 创建险种成功，ID: ${testInsuranceTypeId}`);
      console.log(`   险种名称: ${response.data.data.name}`);
    } else {
      throw new Error('创建险种失败');
    }
  } catch (error) {
    throw new Error(`创建险种失败: ${error.response?.data?.message || error.message}`);
  }
  
  console.log('');
}

// 4. 测试获取单个险种
async function testGetInsuranceTypeById() {
  console.log('🔍 测试获取单个险种...');
  
  if (!testInsuranceTypeId) {
    throw new Error('没有可用的测试险种ID');
  }
  
  try {
    const response = await api.get(`/insurance-types/${testInsuranceTypeId}`);
    
    if (response.data.success && response.data.data) {
      console.log(`✅ 获取险种详情成功`);
      console.log(`   险种名称: ${response.data.data.name}`);
      console.log(`   适用牲畜: ${response.data.data.applicable_livestock}`);
      console.log(`   保险期限: ${response.data.data.insurance_term}`);
    } else {
      throw new Error('获取险种详情失败');
    }
  } catch (error) {
    throw new Error(`获取险种详情失败: ${error.response?.data?.message || error.message}`);
  }
  
  console.log('');
}

// 5. 测试更新险种
async function testUpdateInsuranceType() {
  console.log('✏️ 测试更新险种...');
  
  if (!testInsuranceTypeId) {
    throw new Error('没有可用的测试险种ID');
  }
  
  const updateData = {
    description: '这是一个更新后的测试险种描述',
    premium_rate: 0.08
  };
  
  try {
    const response = await api.put(`/insurance-types/${testInsuranceTypeId}`, updateData);
    
    if (response.data.success && response.data.data) {
      console.log(`✅ 更新险种成功`);
      console.log(`   新描述: ${response.data.data.description}`);
      console.log(`   新费率: ${response.data.data.premium_rate}`);
    } else {
      throw new Error('更新险种失败');
    }
  } catch (error) {
    throw new Error(`更新险种失败: ${error.response?.data?.message || error.message}`);
  }
  
  console.log('');
}

// 6. 测试更新险种状态
async function testUpdateInsuranceTypeStatus() {
  console.log('🔄 测试更新险种状态...');
  
  if (!testInsuranceTypeId) {
    throw new Error('没有可用的测试险种ID');
  }
  
  const statusData = {
    status: 'active',
    on_sale_status: true
  };
  
  try {
    const response = await api.patch(`/insurance-types/${testInsuranceTypeId}/status`, statusData);
    
    if (response.data.success && response.data.data) {
      console.log(`✅ 更新险种状态成功`);
      console.log(`   状态: ${response.data.data.status}`);
      console.log(`   在售状态: ${response.data.data.on_sale_status}`);
    } else {
      throw new Error('更新险种状态失败');
    }
  } catch (error) {
    throw new Error(`更新险种状态失败: ${error.response?.data?.message || error.message}`);
  }
  
  console.log('');
}

// 7. 测试删除险种
async function testDeleteInsuranceType() {
  console.log('🗑️ 测试删除险种...');
  
  if (!testInsuranceTypeId) {
    throw new Error('没有可用的测试险种ID');
  }
  
  try {
    const response = await api.delete(`/insurance-types/${testInsuranceTypeId}`);
    
    if (response.data.success) {
      console.log(`✅ 删除险种成功，ID: ${testInsuranceTypeId}`);
    } else {
      throw new Error('删除险种失败');
    }
  } catch (error) {
    throw new Error(`删除险种失败: ${error.response?.data?.message || error.message}`);
  }
  
  console.log('');
}

// 运行测试
if (require.main === module) {
  runTests().catch(error => {
    console.error('测试运行失败:', error.message);
    process.exit(1);
  });
}

module.exports = {
  runTests,
  testLogin,
  testGetInsuranceTypes,
  testCreateInsuranceType,
  testGetInsuranceTypeById,
  testUpdateInsuranceType,
  testUpdateInsuranceTypeStatus,
  testDeleteInsuranceType
};