const { sequelize } = require('../config/database');
const seedProjects = require('./seed-projects');

async function setupProjects() {
  try {
    console.log('🚀 开始设置项目清单功能...\n');
    
    // 1. 测试数据库连接
    console.log('1️⃣ 测试数据库连接...');
    await sequelize.authenticate();
    console.log('✅ 数据库连接成功\n');
    
    // 2. 运行项目表迁移
    console.log('2️⃣ 运行项目表迁移...');
    try {
      const { QueryInterface } = require('sequelize');
      const queryInterface = sequelize.getQueryInterface();
      
      // 检查表是否已存在
      const tableExists = await queryInterface.showAllTables().then(tables => 
        tables.includes('projects')
      );
      
      if (!tableExists) {
        // 运行迁移
        const migration = require('../migrations/20241220000002-create-projects');
        await migration.up(queryInterface, sequelize);
        console.log('✅ 项目表创建成功\n');
      } else {
        console.log('✅ 项目表已存在\n');
      }
    } catch (error) {
      console.error('❌ 项目表迁移失败:', error.message);
      throw error;
    }
    
    // 3. 创建项目测试数据
    console.log('3️⃣ 创建项目测试数据...');
    await seedProjects();
    console.log('✅ 项目测试数据创建完成\n');
    
    // 4. 验证数据
    console.log('4️⃣ 验证项目数据...');
    const { Project } = require('../models');
    const projectCount = await Project.count();
    const supervisionCount = await Project.count({ where: { status: 'supervision' } });
    const completedCount = await Project.count({ where: { status: 'completed' } });
    
    console.log(`   总项目数: ${projectCount}`);
    console.log(`   监管中项目: ${supervisionCount}`);
    console.log(`   已结项项目: ${completedCount}`);
    console.log('✅ 项目数据验证完成\n');
    
    console.log('🎉 项目清单功能设置完成！');
    console.log('📝 接下来可以：');
    console.log('   1. 启动后端服务器: npm start');
    console.log('   2. 运行API测试: node test-projects-api.js');
    console.log('   3. 在前端访问项目清单页面');
    
  } catch (error) {
    console.error('❌ 设置项目清单功能失败:', error);
    throw error;
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  setupProjects()
    .then(() => {
      console.log('✅ 脚本执行完成');
      process.exit(0);
    })
    .catch((error) => {
      console.error('❌ 脚本执行失败:', error);
      process.exit(1);
    });
}

module.exports = setupProjects;
