/**
 * 删除指定 UID 的用户及其所有相关数据
 * 
 * 使用方法: node src/scripts/deleteUserByUid.js <uid>
 * 例如: node src/scripts/deleteUserByUid.js 560170
 */

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

async function deleteUserByUid(uid) {
  console.log(`\n🔍 查找 UID 为 ${uid} 的用户...\n`);
  
  // 查找用户
  const user = await User.findOne({ where: { uid } });
  
  if (!user) {
    console.log(`❌ 未找到 UID 为 ${uid} 的用户`);
    return false;
  }
  
  console.log(`✅ 找到用户:`);
  console.log(`   ID: ${user.id}`);
  console.log(`   UID: ${user.uid}`);
  console.log(`   昵称: ${user.nickname || 'N/A'}`);
  console.log(`   手机: ${user.phone || 'N/A'}`);
  console.log(`   邀请码: ${user.invitationCode || 'N/A'}`);
  console.log(`   余额: ${user.balance}`);
  console.log(`   创建时间: ${user.createdAt}`);
  console.log('');
  
  const userId = user.id;
  
  // 开始事务
  const transaction = await sequelize.transaction();
  
  try {
    // 1. 删除佣金记录（作为邀请者或被邀请者）
    const commissionCount = await Commission.destroy({
      where: {
        [require('sequelize').Op.or]: [
          { inviterId: userId },
          { inviteeId: userId }
        ]
      },
      transaction
    });
    console.log(`   🗑️  删除佣金记录: ${commissionCount} 条`);
    
    // 2. 删除支付订单
    const paymentOrderCount = await PaymentOrder.destroy({
      where: { userId },
      transaction
    });
    console.log(`   🗑️  删除支付订单: ${paymentOrderCount} 条`);
    
    // 3. 删除邀请记录（作为邀请者或被邀请者）
    const invitationCount = await Invitation.destroy({
      where: {
        [require('sequelize').Op.or]: [
          { inviterId: userId },
          { inviteeId: userId }
        ]
      },
      transaction
    });
    console.log(`   🗑️  删除邀请记录: ${invitationCount} 条`);
    
    // 4. 删除提现记录
    const withdrawalCount = await Withdrawal.destroy({
      where: { userId },
      transaction
    });
    console.log(`   🗑️  删除提现记录: ${withdrawalCount} 条`);
    
    // 5. 删除通知
    const notificationCount = await Notification.destroy({
      where: { userId },
      transaction
    });
    console.log(`   🗑️  删除通知: ${notificationCount} 条`);
    
    // 6. 删除登录历史
    const loginHistoryCount = await LoginHistory.destroy({
      where: { userId },
      transaction
    });
    console.log(`   🗑️  删除登录历史: ${loginHistoryCount} 条`);
    
    // 7. 删除预约记录
    const appointmentCount = await Appointment.destroy({
      where: { userId },
      transaction
    });
    console.log(`   🗑️  删除预约记录: ${appointmentCount} 条`);
    
    // 8. 清除其他用户的 invitedBy 引用（如果有用户是被此用户邀请的）
    const invitedByCount = await User.update(
      { invitedBy: null },
      { where: { invitedBy: userId }, transaction }
    );
    console.log(`   🔄 清除被邀请用户的引用: ${invitedByCount[0]} 条`);
    
    // 9. 最后删除用户
    await User.destroy({
      where: { id: userId },
      transaction
    });
    console.log(`   🗑️  删除用户: 1 条`);
    
    // 提交事务
    await transaction.commit();
    
    console.log(`\n✅ 用户 ${uid} 及其所有相关数据已成功删除!\n`);
    return true;
    
  } catch (error) {
    // 回滚事务
    await transaction.rollback();
    console.error(`\n❌ 删除失败:`, error.message);
    throw error;
  }
}

// 主函数
async function main() {
  const uid = process.argv[2];
  
  if (!uid) {
    console.log('使用方法: node src/scripts/deleteUserByUid.js <uid>');
    console.log('例如: node src/scripts/deleteUserByUid.js 560170');
    process.exit(1);
  }
  
  try {
    await deleteUserByUid(uid);
    process.exit(0);
  } catch (error) {
    console.error('执行失败:', error);
    process.exit(1);
  }
}

main();
