import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function clearDepartments() {
  console.log('🚀 Clearing all departments...\n');

  try {
    // 1. 统计当前数据
    const departmentCount = await prisma.department.count();
    const usersWithDept = await prisma.user.count({
      where: { departmentId: { not: null } },
    });

    console.log('📊 Current data:');
    console.log(`   - Departments: ${departmentCount}`);
    console.log(`   - Users with department: ${usersWithDept}`);
    console.log('');

    if (departmentCount === 0) {
      console.log('✅ No departments to clear.');
      return;
    }

    // 2. 清空用户的部门关联
    console.log('📝 Clearing user department associations...');
    const updateResult = await prisma.user.updateMany({
      where: { departmentId: { not: null } },
      data: { departmentId: null },
    });
    console.log(`   - Updated ${updateResult.count} users`);

    // 3. 删除所有部门（从子部门开始，避免外键约束问题）
    console.log('📝 Deleting departments...');
    
    // 递归删除，先删除没有子部门的
    let deletedTotal = 0;
    let iteration = 0;
    const maxIterations = 20; // 防止无限循环
    
    while (iteration < maxIterations) {
      // 找出没有子部门的部门
      const leafDepartments = await prisma.department.findMany({
        where: {
          children: {
            none: {},
          },
        },
        select: { id: true },
      });

      if (leafDepartments.length === 0) {
        break;
      }

      // 删除这些叶子部门
      const deleteResult = await prisma.department.deleteMany({
        where: {
          id: { in: leafDepartments.map((d) => d.id) },
        },
      });

      deletedTotal += deleteResult.count;
      console.log(`   - Iteration ${iteration + 1}: Deleted ${deleteResult.count} departments`);
      iteration++;
    }

    console.log(`   - Total deleted: ${deletedTotal} departments`);

    // 4. 验证结果
    const remainingDepts = await prisma.department.count();
    const remainingUsersWithDept = await prisma.user.count({
      where: { departmentId: { not: null } },
    });

    console.log('\n' + '='.repeat(60));
    console.log('🎉 Department clearing complete!');
    console.log('='.repeat(60));
    console.log('\n📊 Final state:');
    console.log(`   - Remaining departments: ${remainingDepts}`);
    console.log(`   - Users with department: ${remainingUsersWithDept}`);
    console.log('\n✅ All users can now be reassigned to new departments.');
    console.log('');

  } catch (error) {
    console.error('❌ Error clearing departments:', error);
    throw error;
  } finally {
    await prisma.$disconnect();
  }
}

// 执行脚本
clearDepartments();
