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 fixModelFile(filePath) {
  try {
    let content = fs.readFileSync(filePath, 'utf8');
    const originalContent = content;
    
    // 替换 DataTypes 为 Sequelize
    content = content.replace(/DataTypes/g, 'Sequelize');
    
    // 修复 module.exports 格式
    // 匹配: module.exports = (sequelize, DataTypes) => { const model = sequelize.define(...) }
    const pattern1 = /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(pattern1, (match, modelName, tableName, fields) => {
      return `module.exports = (db) => {
  return db.define("${tableName}", {${fields}
  });
};`;
    });
    
    // 匹配: module.exports = (sequelize, DataTypes) => { const model = sequelize.define(...); return model; }
    const pattern2 = /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(pattern2, (match, modelName, tableName, fields) => {
      return `module.exports = (db) => {
  return db.define("${tableName}", {${fields}
  });
};`;
    });
    
    // 匹配: module.exports = (sequelize, DataTypes) => { return sequelize.define(...); }
    const pattern3 = /module\.exports\s*=\s*\(sequelize,\s*DataTypes\)\s*=>\s*\{\s*return\s+sequelize\.define\('([^']+)',\s*\{([\s\S]*?)\}\);\s*\};/g;
    
    content = content.replace(pattern3, (match, tableName, fields) => {
      return `module.exports = (db) => {
  return db.define("${tableName}", {${fields}
  });
};`;
    });
    
    // 匹配: module.exports = (sequelize, Sequelize) => { ... }
    const pattern4 = /module\.exports\s*=\s*\(sequelize,\s*Sequelize\)\s*=>\s*\{\s*const\s+(\w+)\s*=\s*sequelize\.define\('([^']+)',\s*\{([\s\S]*?)\}\);\s*\/\/[^}]*return\s+\1;\s*\};/g;
    
    content = content.replace(pattern4, (match, modelName, tableName, fields) => {
      return `module.exports = (db) => {
  return db.define("${tableName}", {${fields}
  });
};`;
    });
    
    // 匹配: module.exports = (sequelize, Sequelize) => { const model = sequelize.define(...); return model; }
    const pattern5 = /module\.exports\s*=\s*\(sequelize,\s*Sequelize\)\s*=>\s*\{\s*const\s+(\w+)\s*=\s*sequelize\.define\('([^']+)',\s*\{([\s\S]*?)\}\);\s*return\s+\1;\s*\};/g;
    
    content = content.replace(pattern5, (match, modelName, 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 (fixModelFile(filePath)) {
      fixedCount++;
    }
  });
  
  console.log(`修复完成，共修复 ${fixedCount} 个文件`);
}

main();
