/**
 * Check and Clean Duplicate Users Script
 * Find duplicate users with same wechatOpenId and clean them
 */

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

async function checkDuplicateUsers() {
  console.log('🔍 检查重复用户...\n');

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

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

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

    // Group by wechatOpenId
    const grouped = {};
    users.forEach(user => {
      const openId = user.wechatOpenId;
      if (!grouped[openId]) {
        grouped[openId] = [];
      }
      grouped[openId].push(user);
    });

    // Find duplicates
    const duplicates = Object.entries(grouped).filter(([_, users]) => users.length > 1);

    if (duplicates.length === 0) {
      console.log('✅ 没有发现重复用户\n');
      return;
    }

    console.log(`⚠️  发现 ${duplicates.length} 个重复的 wechatOpenId:\n`);

    duplicates.forEach(([openId, users]) => {
      console.log(`📱 wechatOpenId: ${openId}`);
      console.log(`   重复次数: ${users.length}`);
      users.forEach((user, index) => {
        console.log(`   ${index + 1}. ID: ${user.id}`);
        console.log(`      昵称: ${user.nickname || 'N/A'}`);
        console.log(`      手机: ${user.phone || 'N/A'}`);
        console.log(`      余额: ¥${user.balance}`);
        console.log(`      创建时间: ${user.createdAt}`);
      });
      console.log('');
    });

    // Ask if user wants to clean
    console.log('💡 建议操作:');
    console.log('   对于每个重复的 wechatOpenId，保留最早创建的用户，删除其他重复记录\n');

    // In production, you would prompt for confirmation
    // For now, just show what would be deleted
    console.log('🗑️  将要删除的用户:');
    let deleteCount = 0;
    duplicates.forEach(([openId, users]) => {
      // Keep the first (oldest) user, delete the rest
      const toDelete = users.slice(1);
      toDelete.forEach(user => {
        console.log(`   - ${user.nickname || 'N/A'} (${user.id}) - 创建于 ${user.createdAt}`);
        deleteCount++;
      });
    });

    console.log(`\n   总共将删除 ${deleteCount} 个重复用户\n`);

    // Uncomment to actually delete
    // console.log('🔧 开始清理...');
    // for (const [openId, users] of duplicates) {
    //   const toDelete = users.slice(1);
    //   for (const user of toDelete) {
    //     await User.destroy({ where: { id: user.id } });
    //     console.log(`   ✅ 已删除: ${user.nickname || 'N/A'} (${user.id})`);
    //   }
    // }
    // console.log('\n✅ 清理完成！');

    console.log('⚠️  注意: 此脚本当前只显示重复数据，不会实际删除');
    console.log('   如需删除，请取消注释脚本中的删除代码\n');

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

// Run check
checkDuplicateUsers();
