/**
 * Check and fix user UIDs
 */

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

async function checkUserUid() {
  console.log('🔍 检查用户 UID...\n');

  try {
    await sequelize.authenticate();
    console.log('✅ 数据库连接成功\n');

    // Get all users
    const users = await User.findAll({
      attributes: ['id', 'uid', 'nickname', 'createdAt']
    });

    console.log(`📊 总用户数: ${users.length}\n`);

    for (const user of users) {
      console.log(`用户: ${user.nickname || 'N/A'}`);
      console.log(`  ID: ${user.id}`);
      console.log(`  UID: ${user.uid || '(无)'}`);
      console.log(`  创建时间: ${user.createdAt}\n`);

      // 如果没有 uid，生成一个
      if (!user.uid) {
        console.log('  ⚠️  该用户没有 UID，正在生成...');
        
        // 生成唯一的 6 位数字 UID
        let uid;
        let exists = true;
        let nextUid = 100001;
        
        while (exists) {
          uid = String(nextUid);
          const existing = await User.findOne({ where: { uid } });
          if (!existing) {
            exists = false;
          } else {
            nextUid++;
          }
        }
        
        await user.update({ uid });
        console.log(`  ✅ 已生成 UID: ${uid}\n`);
      }
    }

    console.log('✅ 检查完成！\n');

  } catch (error) {
    console.error('❌ 检查过程中出错:', error.message);
    console.error(error);
  } finally {
    await sequelize.close();
  }
}

// Run check
checkUserUid();
