const fs = require('fs');
const path = require('path');

// 递归查找所有 .js 文件
function findJsFiles(dir) {
  let results = [];
  const list = fs.readdirSync(dir);
  
  list.forEach(file => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);
    
    if (stat && stat.isDirectory()) {
      results = results.concat(findJsFiles(filePath));
    } else if (file.endsWith('.js')) {
      results.push(filePath);
    }
  });
  
  return results;
}

// 修复 model 定义
function fixModelDefinition(filePath) {
  try {
    let content = fs.readFileSync(filePath, 'utf8');
    const originalContent = content;
    
    // 检查是否已经是正确的格式
    if (content.includes('module.exports = (db) => {')) {
      console.log(`跳过已正确格式的文件: ${filePath}`);
      return false;
    }
    
    // 替换 DataTypes 为 Sequelize
    content = content.replace(/DataTypes/g, 'Sequelize');
    
    // 替换 module.exports 格式
    // 从: module.exports = (sequelize, DataTypes) => { const model = sequelize.define(...) }
    // 到: module.exports = (db) => { return db.define(...) }
    
    const sequelizeDefinePattern = /module\.exports\s*=\s*\(sequelize,\s*DataTypes\)\s*=>\s*\{\s*const\s+(\w+)\s*=\s*sequelize\.define\('([^']+)',\s*\{([\s\S]*?)\}\);\s*return\s+\1;\s*\};/g;
    
    content = content.replace(sequelizeDefinePattern, (match, modelName, tableName, fields) => {
      return `module.exports = (db) => {
  return db.define("${tableName}", {${fields}
  });
};`;
    });
    
    // 如果上面的模式没有匹配到，尝试其他模式
    if (content === originalContent) {
      const simpleDefinePattern = /module\.exports\s*=\s*\(sequelize,\s*DataTypes\)\s*=>\s*\{\s*return\s+sequelize\.define\('([^']+)',\s*\{([\s\S]*?)\}\);\s*\};/g;
      
      content = content.replace(simpleDefinePattern, (match, tableName, fields) => {
        return `module.exports = (db) => {
  return db.define("${tableName}", {${fields}
  });
};`;
      });
    }
    
    // 清理多余的空行
    content = content.replace(/\n\s*\n\s*\n/g, '\n\n');
    
    if (content !== originalContent) {
      fs.writeFileSync(filePath, content, 'utf8');
      console.log(`已修复: ${filePath}`);
      return true;
    }
    
    return false;
  } catch (error) {
    console.error(`处理文件失败 ${filePath}:`, error.message);
    return false;
  }
}

// 主函数
function main() {
  const modelDir = path.join(__dirname, 'api', 'model');
  
  if (!fs.existsSync(modelDir)) {
    console.error('模型目录不存在:', modelDir);
    return;
  }
  
  const jsFiles = findJsFiles(modelDir);
  let fixedCount = 0;
  
  console.log(`找到 ${jsFiles.length} 个模型文件`);
  
  jsFiles.forEach(filePath => {
    if (fixModelDefinition(filePath)) {
      fixedCount++;
    }
  });
  
  console.log(`修复完成，共修复 ${fixedCount} 个文件`);
}

main();
