/**
 * Migration: Add uid field to user table
 * 为用户表添加6位数字UID字段
 */

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

async function up() {
  const queryInterface = sequelize.getQueryInterface();
  
  console.log('🔄 开始添加 uid 字段...');
  
  try {
    // 检查字段是否已存在
    const tableInfo = await queryInterface.describeTable('user');
    
    if (!tableInfo.uid) {
      // 添加 uid 字段
      await queryInterface.addColumn('user', 'uid', {
        type: 'VARCHAR(6)',
        allowNull: true,
        unique: true,
        comment: '6位数字用户ID，用于展示',
      });
      console.log('✅ uid 字段添加成功');
    } else {
      console.log('ℹ️  uid 字段已存在，跳过');
    }
    
    // 为现有用户生成 uid
    const [users] = await sequelize.query(
      'SELECT id FROM user WHERE uid IS NULL'
    );
    
    if (users.length > 0) {
      console.log(`🔄 为 ${users.length} 个用户生成 uid...`);
      
      let nextUid = 100001;
      
      for (const user of users) {
        // 确保 uid 唯一
        let uid = String(nextUid);
        let exists = true;
        
        while (exists) {
          const [existing] = await sequelize.query(
            'SELECT id FROM user WHERE uid = ?',
            { replacements: [uid] }
          );
          
          if (existing.length === 0) {
            exists = false;
          } else {
            nextUid++;
            uid = String(nextUid);
          }
        }
        
        await sequelize.query(
          'UPDATE user SET uid = ? WHERE id = ?',
          { replacements: [uid, user.id] }
        );
        
        console.log(`   用户 ${user.id} -> UID: ${uid}`);
        nextUid++;
      }
      
      console.log('✅ 所有用户 uid 生成完成');
    } else {
      console.log('ℹ️  没有需要生成 uid 的用户');
    }
    
    console.log('✅ 迁移完成！');
    
  } catch (error) {
    console.error('❌ 迁移失败:', error.message);
    throw error;
  }
}

async function down() {
  const queryInterface = sequelize.getQueryInterface();
  
  console.log('🔄 开始回滚 uid 字段...');
  
  try {
    await queryInterface.removeColumn('user', 'uid');
    console.log('✅ uid 字段已删除');
  } catch (error) {
    console.error('❌ 回滚失败:', error.message);
    throw error;
  }
}

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

module.exports = { up, down };
