const { sequelize } = require('../config/database');
const { User, Role, InsuranceApplication, InsuranceType, Policy, Claim } = require('../models');

async function initDatabase() {
  try {
    console.log('🔄 开始初始化数据库...');
    
    // 测试数据库连接
    console.log('🔗 测试数据库连接...');
    await sequelize.authenticate();
    console.log('✅ 数据库连接成功');
    
    // 先删除所有表（如果存在）
    console.log('🗑️  清理现有表结构...');
    // 禁用外键约束
    await sequelize.query('SET FOREIGN_KEY_CHECKS = 0');
    
    await Claim.drop();
    await Policy.drop();
    await InsuranceApplication.drop();
    await InsuranceType.drop();
    await User.drop();
    await Role.drop();
    
    // 启用外键约束
    await sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
    console.log('✅ 现有表结构清理完成');
    
    // 按顺序创建表
    console.log('🗄️  创建角色表...');
    await Role.sync();
    
    console.log('🗄️  创建用户表...');
    await User.sync();
    
    console.log('🗄️  创建保险类型表...');
    await InsuranceType.sync();
    
    console.log('🗄️  创建保险申请表...');
    await InsuranceApplication.sync();
    
    console.log('🗄️  创建保单表...');
    await Policy.sync();
    
    console.log('🗄️  创建理赔表...');
    await Claim.sync();
    
    console.log('✅ 所有表创建完成');
    
    // 创建默认角色
    console.log('👥 创建默认角色...');
    const roles = await Role.bulkCreate([
      { name: 'admin', description: '系统管理员', permissions: JSON.stringify(['*']) },
      { name: 'agent', description: '保险代理人', permissions: JSON.stringify(['insurance:read', 'insurance:create', 'policy:read']) },
      { name: 'customer', description: '客户', permissions: JSON.stringify(['insurance:create', 'policy:read:self', 'claim:create:self']) },
      { name: 'reviewer', description: '审核员', permissions: JSON.stringify(['insurance:review', 'claim:review']) }
    ]);
    console.log('✅ 默认角色创建完成');
    
    // 创建默认保险类型
    console.log('📋 创建默认保险类型...');
    const insuranceTypes = await InsuranceType.bulkCreate([
      { 
        name: '人寿保险', 
        description: '提供生命保障的保险产品',
        coverage_amount_min: 10000,
        coverage_amount_max: 1000000,
        premium_rate: 0.0025,
        status: 'active'
      },
      { 
        name: '健康保险', 
        description: '提供医疗保障的保险产品',
        coverage_amount_min: 5000,
        coverage_amount_max: 500000,
        premium_rate: 0.003,
        status: 'active'
      },
      { 
        name: '财产保险', 
        description: '提供财产保障的保险产品',
        coverage_amount_min: 1000,
        coverage_amount_max: 2000000,
        premium_rate: 0.0015,
        status: 'active'
      },
      { 
        name: '车险', 
        description: '提供车辆保障的保险产品',
        coverage_amount_min: 500,
        coverage_amount_max: 1000000,
        premium_rate: 0.002,
        status: 'active'
      }
    ]);
    console.log('✅ 默认保险类型创建完成');
    
    console.log('🎉 数据库初始化完成！');
    
  } catch (error) {
    console.error('❌ 数据库初始化失败:', error);
    process.exit(1);
  } finally {
    await sequelize.close();
  }
}

// 如果是直接运行此脚本
if (require.main === module) {
  initDatabase();
}

module.exports = initDatabase;