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

async function runMigration() {
  try {
    console.log('开始运行数据库迁移...');
    
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('✅ 数据库连接成功');
    
    // 获取所有迁移文件
    const migrationsPath = path.join(__dirname, 'migrations');
    const migrationFiles = fs.readdirSync(migrationsPath)
      .filter(file => file.endsWith('.js'))
      .sort();
    
    console.log(`找到 ${migrationFiles.length} 个迁移文件`);
    
    // 确保 SequelizeMeta 表存在
    await sequelize.query(`
      CREATE TABLE IF NOT EXISTS \`SequelizeMeta\` (
        \`name\` varchar(255) COLLATE utf8mb3_unicode_ci NOT NULL,
        PRIMARY KEY (\`name\`),
        UNIQUE KEY \`name\` (\`name\`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
    `);
    
    // 检查哪些迁移已经运行过
    const [executedMigrations] = await sequelize.query(
      'SELECT name FROM SequelizeMeta ORDER BY name'
    );
    const executedNames = executedMigrations.map(row => row.name);
    
    // 运行未执行的迁移
    for (const file of migrationFiles) {
      if (!executedNames.includes(file)) {
        console.log(`正在运行迁移: ${file}`);
        
        try {
          const migration = require(path.join(migrationsPath, file));
          await migration.up(sequelize.getQueryInterface(), sequelize.constructor);
          
          // 记录迁移已执行
          await sequelize.query(
            'INSERT INTO SequelizeMeta (name) VALUES (?)',
            { replacements: [file] }
          );
          
          console.log(`✅ 迁移 ${file} 执行成功`);
        } catch (error) {
          console.error(`❌ 迁移 ${file} 执行失败:`, error);
          throw error;
        }
      } else {
        console.log(`⏭️  迁移 ${file} 已执行，跳过`);
      }
    }
    
    console.log('🎉 所有迁移执行完成！');
    
  } catch (error) {
    console.error('❌ 迁移执行失败:', error);
    throw error;
  } finally {
    await sequelize.close();
  }
}

// 运行迁移
runMigration().catch(error => {
  console.error('迁移过程中发生错误:', error);
  process.exit(1);
});