const { Expense } = require('./models');

async function fixExpenseMedia() {
  try {
    console.log('开始修复经费媒体数据...');
    
    const expenses = await Expense.findAll();
    console.log(`找到 ${expenses.length} 条经费记录`);
    
    let fixedCount = 0;
    
    for (const expense of expenses) {
      let needUpdate = false;
      let media = expense.media || [];
      
      // 检查是否有异常数据
      if (Array.isArray(media) && media.length > 5) {
        console.log(`经费 #${expense.id} 有 ${media.length} 个媒体文件，超过限制`);
        media = media.slice(0, 5);
        needUpdate = true;
      }
      
      // 检查是否有无效的媒体项
      const validMedia = media.filter(item => {
        return item && item.url && (item.type === 'image' || item.type === 'video');
      });
      
      if (validMedia.length !== media.length) {
        console.log(`经费 #${expense.id} 有无效媒体项，从 ${media.length} 清理到 ${validMedia.length}`);
        media = validMedia;
        needUpdate = true;
      }
      
      if (needUpdate) {
        await expense.update({ media });
        fixedCount++;
        console.log(`✓ 修复经费 #${expense.id}`);
      }
    }
    
    console.log(`\n修复完成！共修复 ${fixedCount} 条记录`);
    process.exit(0);
  } catch (error) {
    console.error('修复失败:', error);
    process.exit(1);
  }
}

fixExpenseMedia();
