const { sequelize } = require('../config/database');
const fs = require('fs');
const path = require('path');

async function executeLivestockSchema() {
  try {
    // 确保使用正确的数据库
    await sequelize.query('USE insurance_data');
    console.log('✅ 已切换到 insurance_data 数据库');
    
    // 读取SQL文件
    const sqlFile = path.join(__dirname, 'livestock_insurance_schema.sql');
    const sqlContent = fs.readFileSync(sqlFile, 'utf8');
    
    // 分割SQL语句（按分号分割，但忽略注释中的分号）
    const statements = sqlContent
      .split('\n')
      .filter(line => !line.trim().startsWith('--') && line.trim() !== '')
      .join('\n')
      .split(';')
      .filter(statement => statement.trim() !== '');
    
    console.log('开始执行生资保单数据库表创建...');
    
    // 逐个执行SQL语句
    for (let i = 0; i < statements.length; i++) {
      const statement = statements[i].trim();
      if (statement) {
        try {
          console.log(`执行语句 ${i + 1}/${statements.length}...`);
          await sequelize.query(statement);
          console.log(`✅ 语句 ${i + 1} 执行成功`);
        } catch (error) {
          console.error(`❌ 语句 ${i + 1} 执行失败:`, error.message);
          console.log('失败的语句:', statement.substring(0, 100) + '...');
        }
      }
    }
    
    console.log('✅ 生资保单数据库表创建完成');
    
    // 验证表是否创建成功
    const [results] = await sequelize.query("SHOW TABLES LIKE 'livestock_%'");
    console.log('创建的表:', results.map(row => Object.values(row)[0]));
    
  } catch (error) {
    console.error('❌ 执行失败:', error.message);
  } finally {
    await sequelize.close();
  }
}

executeLivestockSchema();