/**
 * Clean Duplicate Users Script
 * Keep only the oldest user for each unique set of characteristics
 */

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

async function cleanDuplicateUsers() {
  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`);

    if (users.length <= 1) {
      console.log('✅ 只有一个或没有用户，无需清理\n');
      return;
    }

    // Group users by similar characteristics (same nickname or similar creation time)
    // Since they all have different wechatOpenId, we'll identify duplicates by:
    // 1. Same nickname
    // 2. Created within 1 hour of each other
    // 3. Same balance (0.00)

    const grouped = {};
    users.forEach(user => {
      const key = user.nickname || 'unknown';
      if (!grouped[key]) {
        grouped[key] = [];
      }
      grouped[key].push(user);
    });

    // Find potential duplicates (same nickname with multiple users)
    const potentialDuplicates = Object.entries(grouped).filter(([_, users]) => users.length > 1);

    if (potentialDuplicates.length === 0) {
      console.log('✅ 没有发现明显的重复用户（基于昵称）\n');
      
      // Show all users for manual review
      console.log('📋 所有用户列表:');
      users.forEach((user, index) => {
        console.log(`${index + 1}. ${user.nickname || 'N/A'} (${user.id})`);
        console.log(`   OpenId: ${user.wechatOpenId}`);
        console.log(`   创建时间: ${user.createdAt}`);
        console.log(`   余额: ¥${user.balance}\n`);
      });
      
      console.log('💡 如果这些是同一个用户的重复记录，请手动确认后运行清理\n');
      return;
    }

    console.log(`⚠️  发现 ${potentialDuplicates.length} 组可能重复的用户:\n`);

    let totalToDelete = 0;
    const usersToDelete = [];

    potentialDuplicates.forEach(([nickname, users]) => {
      console.log(`👤 昵称: ${nickname}`);
      console.log(`   重复次数: ${users.length}`);
      
      // Keep the first (oldest) user
      const keepUser = users[0];
      const deleteUsers = users.slice(1);
      
      console.log(`   ✅ 保留: ${keepUser.id} (创建于 ${keepUser.createdAt})`);
      
      deleteUsers.forEach(user => {
        console.log(`   ❌ 删除: ${user.id} (创建于 ${user.createdAt})`);
        usersToDelete.push(user.id);
        totalToDelete++;
      });
      console.log('');
    });

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

    // Confirm deletion
    console.log('⚠️  警告: 即将删除用户及其相关数据（预约、提现、邀请记录等）\n');
    console.log('🔧 开始清理...\n');

    // Delete related data first
    for (const userId of usersToDelete) {
      // Delete appointments
      const appointmentCount = await Appointment.count({ where: { userId } });
      if (appointmentCount > 0) {
        await Appointment.destroy({ where: { userId } });
        console.log(`   删除 ${appointmentCount} 条预约记录 (用户 ${userId})`);
      }

      // Delete withdrawals
      const withdrawalCount = await Withdrawal.count({ where: { userId } });
      if (withdrawalCount > 0) {
        await Withdrawal.destroy({ where: { userId } });
        console.log(`   删除 ${withdrawalCount} 条提现记录 (用户 ${userId})`);
      }

      // Delete invitations (as inviter)
      const invitationCount = await Invitation.count({ where: { inviterId: userId } });
      if (invitationCount > 0) {
        await Invitation.destroy({ where: { inviterId: userId } });
        console.log(`   删除 ${invitationCount} 条邀请记录 (用户 ${userId})`);
      }

      // Delete invitations (as invitee)
      const inviteeCount = await Invitation.count({ where: { inviteeId: userId } });
      if (inviteeCount > 0) {
        await Invitation.destroy({ where: { inviteeId: userId } });
        console.log(`   删除 ${inviteeCount} 条被邀请记录 (用户 ${userId})`);
      }

      // Delete login history
      const loginCount = await LoginHistory.count({ where: { userId } });
      if (loginCount > 0) {
        await LoginHistory.destroy({ where: { userId } });
        console.log(`   删除 ${loginCount} 条登录记录 (用户 ${userId})`);
      }

      // Finally delete the user
      await User.destroy({ where: { id: userId } });
      console.log(`   ✅ 已删除用户 ${userId}\n`);
    }

    console.log('✅ 清理完成！\n');

    // Show remaining users
    const remainingUsers = await User.count();
    console.log(`📊 剩余用户数: ${remainingUsers}\n`);

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

// Run cleanup
cleanDuplicateUsers();
