import { Injectable, NotFoundException, BadRequestException, Logger } from '@nestjs/common';
import { PrismaService } from '@core/database/prisma/prisma.service';
import {
  CreateDepartmentDto,
  UpdateDepartmentDto,
  DepartmentQueryDto,
  BatchCreateDepartmentDto,
} from './dto/department.dto';
import { AddDepartmentMemberDto, AddDepartmentMembersDto } from './dto/add-member.dto';
import {
  IamDepartmentCodeExistsException,
  IamDepartmentHasChildrenException,
  IamDepartmentHasUsersException,
} from '../exceptions';

@Injectable()
export class DepartmentsService {
  private readonly logger = new Logger(DepartmentsService.name);

  constructor(private prisma: PrismaService) {}

  /**
   * Check for circular reference in department hierarchy
   */
  private async checkCircularReference(departmentId: string, newParentId: string): Promise<boolean> {
    if (departmentId === newParentId) {
      return true;
    }

    let currentId: string | null = newParentId;
    const maxDepth = 20;
    let depth = 0;

    while (currentId && depth < maxDepth) {
      const deptRecord: { parentId: string | null } | null = await this.prisma.department.findUnique({
        where: { id: currentId },
        select: { parentId: true },
      });

      if (!deptRecord) break;

      if (deptRecord.parentId === departmentId) {
        return true;
      }

      currentId = deptRecord.parentId;
      depth++;
    }

    return false;
  }

  /**
   * Create department/organization
   * 
   * v2.1 架构变更:
   * - 必须提供 organizationId
   * - 区域信息通过 organization 继承,不再在 Department 层管理
   * - regionIds 和 defaultRegionId 参数已废弃 (向后兼容但会被忽略)
   * 
   * v2.1.16 新增约束:
   * - 禁止手动创建顶级部门 (parentId 不能为 null)
   * - 根部门由系统在创建组织时自动创建
   */
  async create(createDepartmentDto: CreateDepartmentDto) {
    const { organizationId, name, code, parentId, headId, description, order } = createDepartmentDto;

    // v2.1.16: 禁止手动创建顶级部门 (应用层约束)
    if (!parentId) {
      throw new BadRequestException(
        'Cannot create top-level department manually. Root department is auto-created with organization.'
      );
    }

    // v2.1: 验证组织存在
    const organization = await this.prisma.organization.findUnique({
      where: { id: organizationId, deletedAt: null },
    });

    if (!organization) {
      throw new NotFoundException('Organization not found');
    }

    // v2.1: code 在组织内唯一 (复合唯一键)
    const existing = await this.prisma.department.findUnique({
      where: { 
        organizationId_code: {
          organizationId,
          code,
        }
      },
    });

    if (existing) {
      throw new IamDepartmentCodeExistsException(code);
    }

    // 验证父部门 (现在是必须的)
    const parent = await this.prisma.department.findUnique({
      where: { id: parentId, deletedAt: null },
    });

    if (!parent) {
      throw new NotFoundException('Parent department not found');
    }

    // v2.1: 验证父部门和子部门属于同一组织
    if (parent.organizationId !== organizationId) {
      throw new BadRequestException('Parent department must belong to the same organization');
    }

    // 验证负责人 (如果提供)
    if (headId) {
      const head = await this.prisma.user.findUnique({
        where: { id: headId, deletedAt: null },
      });

      if (!head) {
        throw new NotFoundException('Department head not found');
      }
    }

    // v2.1: 创建部门 (简化，不再管理区域)
    const department = await this.prisma.department.create({
      data: {
        organizationId,
        name,
        code,
        parentId,
        headId,
        description,
        order: order || 0,
      },
      include: {
        organization: {
          select: { 
            id: true, 
            name: true, 
            code: true,
          },
        },
        parent: {
          select: { id: true, name: true, code: true },
        },
      },
    });

    // ✅ 如果设置了负责人，自动将负责人加入部门
    if (headId) {
      try {
        // 检查负责人是否已经在部门中
        const existingMembership = await this.prisma.userDepartment.findFirst({
          where: {
            userId: headId,
            departmentId: department.id,
            leftAt: null,
          },
        });

        // 如果不在，则添加
        if (!existingMembership) {
          await this.prisma.userDepartment.create({
            data: {
              userId: headId,
              departmentId: department.id,
              organizationId: department.organizationId, // v2.1: 必填字段
              isPrimary: true, // 设为主部门
              joinedAt: new Date(),
            },
          });
        }
      } catch (error) {
        this.logger.warn(`Failed to add head ${headId} to department ${department.id}:`, error);
        // 不阻止部门创建流程，只记录警告
      }
    }

    return department;
  }

  /**
   * Batch create departments
   * 批量创建部门，支持事务处理
   */
  async batchCreate(batchCreateDto: BatchCreateDepartmentDto) {
    const { departments } = batchCreateDto;
    const results = {
      success: [] as any[],
      failed: [] as any[],
    };

    // 使用事务批量创建
    for (const deptDto of departments) {
      try {
        const created = await this.create(deptDto);
        results.success.push({
          code: deptDto.code,
          name: deptDto.name,
          id: created.id,
        });
      } catch (error: any) {
        results.failed.push({
          code: deptDto.code,
          name: deptDto.name,
          error: error.message || 'Unknown error',
        });
      }
    }

    return {
      total: departments.length,
      successCount: results.success.length,
      failedCount: results.failed.length,
      results,
    };
  }

  /**
   * Find all departments/organizations
   */
  async findAll(query?: DepartmentQueryDto) {
    const where: any = { deletedAt: null };

    if (query?.keyword) {
      where.OR = [
        { name: { contains: query.keyword, mode: 'insensitive' } },
        { code: { contains: query.keyword, mode: 'insensitive' } },
      ];
    }

    // v2.1: 按区域 ID 过滤（通过 organization 查询）
    if (query?.regionId) {
      where.organization = {
        organizationRegions: {
          some: { regionId: query.regionId },
        },
      };
    }

    if (query?.parentId) {
      where.parentId = query.parentId;
    }
    
    // 只返回顶级组织（用于组织视角选择）
    if (query?.topLevelOnly) {
      where.parentId = null;
    }

    const departments = await this.prisma.department.findMany({
      where,
      include: {
        parent: {
          select: { id: true, name: true, code: true },
        },
        organization: {
          include: {
            organizationRegions: {
              include: {
                region: {
                  select: { id: true, code: true, name: true },
                },
              },
            },
          },
        },
        _count: {
          select: {
            userMemberships: { where: { leftAt: null, user: { deletedAt: null } } },
            children: true,
          },
        },
      }, 
      orderBy: [{ order: 'asc' }, { name: 'asc' }],
    });

    // Get head (department manager) info
    const headIds = departments
      .filter((d) => d.headId)
      .map((d) => d.headId as string);

    const heads = headIds.length > 0
      ? await this.prisma.user.findMany({
          where: { id: { in: headIds }, deletedAt: null },
          select: {
            id: true,
            displayName: true,
            username: true,
            email: true,
            avatar: true,
          },
        })
      : [];

    const headMap = new Map(heads.map((h) => [h.id, h]));

    return departments.map((dept: any) => ({
      ...dept,
      head: dept.headId ? headMap.get(dept.headId) || null : null,
      employeeCount: dept._count?.userMemberships || 0,
      childCount: dept._count?.children || 0,
      // v2.1: 从 organization 获取区域信息（向后兼容）
      regions: (dept as any).organization?.organizationRegions?.map((or: any) => or.region) || [],
    }));
  }

  /**
   * Get top-level organizations (for perspective selection)
   * 
   * v2.1 注意: 此方法返回的是顶级 Department (parentId=null)
   * 实际的 Organization 应该通过 organizations.service 查询
   * 
   * @param regionId - 可选的区域 ID（按 organization.primaryRegionId 过滤）
   */
  async findOrganizations(regionId?: string) {
    const where: any = { 
      deletedAt: null, 
      parentId: null, // 只返回顶级部门
    };
    
    // v2.1: 通过 organization 的 primaryRegionId 过滤
    if (regionId) {
      where.organization = {
        primaryRegionId: regionId,
      };
    }

    const orgs = await this.prisma.department.findMany({
      where,
      include: {
        organization: {
          include: {
            organizationRegions: {
              include: {
                region: {
                  select: { id: true, code: true, name: true },
                },
              },
              orderBy: { isDefault: 'desc' },
            },
          },
        },
        _count: {
          select: {
            userMemberships: { where: { leftAt: null, user: { deletedAt: null, status: 'ACTIVE' } } } as any,
            children: { where: { deletedAt: null } },
          } as any,
        } as any,
      },
      orderBy: [{ order: 'asc' }, { name: 'asc' }],
    });

    // Get head (department manager) info
    const headIds = orgs
      .filter((d) => d.headId)
      .map((d) => d.headId as string);

    const heads = headIds.length > 0
      ? await this.prisma.user.findMany({
          where: { id: { in: headIds }, deletedAt: null },
          select: {
            id: true,
            displayName: true,
            username: true,
            email: true,
            avatar: true,
          },
        })
      : [];

    const headMap = new Map(heads.map((h) => [h.id, h]));

    return orgs.map((org) => {
      // v2.1: 检查 organization 是否有任何区域设为默认
      const hasDefault = (org as any).organization?.organizationRegions?.some((or: any) => or.isDefault) || false;
      return {
        ...org,
        head: org.headId ? headMap.get(org.headId) || null : null,
        employeeCount: (org as any)._count?.userMemberships || 0,
        childCount: (org as any)._count?.children || 0,
        // v2.1: 从 organization 获取区域信息（向后兼容）
        regions: (org as any).organization?.organizationRegions?.map((or: any) => ({
          ...or.region,
          isDefault: or.isDefault,
        })) || [],
        isRegionDefault: hasDefault,
      };
    });
  }

  /**
   * Find department tree for a specific organization
   * @param organizationId - 组织 ID，如果为空则返回所有部门
   */
  async findTree(organizationId?: string) {
    const where: any = { deletedAt: null };
    
    // v2.1: 如果指定了组织 ID，只查询该组织的部门
    if (organizationId) {
      where.organizationId = organizationId;
    }
    
    const departments = await this.prisma.department.findMany({
      where,
      include: {
        organization: {
          include: {
            organizationRegions: {
              include: {
                region: {
                  select: { id: true, code: true, name: true },
                },
              },
            },
          },
        },
        _count: {
          select: {
            userMemberships: { where: { leftAt: null, user: { deletedAt: null, status: 'ACTIVE' } } } as any,
          },
        } as any,
      },
      orderBy: [{ order: 'asc' }, { name: 'asc' }],
    });

    // Get all head (department manager) info
    const headIds = departments
      .filter((d) => d.headId)
      .map((d) => d.headId as string);

    const heads = headIds.length > 0
      ? await this.prisma.user.findMany({
          where: { id: { in: headIds }, deletedAt: null },
          select: {
            id: true,
            displayName: true,
            username: true,
            email: true,
            avatar: true,
          },
        })
      : [];

    const headMap = new Map(heads.map((h) => [h.id, h]));

    // Add head info
    const deptsWithHead = departments.map((dept: any) => ({
      ...dept,
      head: dept.headId ? headMap.get(dept.headId) || null : null,
      employeeCount: dept._count?.userMemberships || 0,
    }));

    // Build tree structure
    const buildTree = (parentId: string | null): any[] => {
      return deptsWithHead
        .filter((dept) => dept.parentId === parentId)
        .map((dept) => ({
          ...dept,
          children: buildTree(dept.id),
        }));
    };

    // 如果指定了组织 ID，返回该组织的部门树（从根部门开始）
    if (organizationId) {
      // 只返回该组织的部门树（从 parentId === null 的根部门开始）
      return buildTree(null);
    }

    // 否则返回所有顶级组织及其子树
    return buildTree(null);
  }

  /**
   * Find department by ID
   */
  async findOne(id: string) {
    const department = await this.prisma.department.findUnique({
      where: { id, deletedAt: null },
      include: {
        parent: {
          select: { id: true, name: true, code: true },
        },
        children: {
          where: { deletedAt: null },
          select: { id: true, name: true, code: true },
        },
        userMemberships: {
          where: { user: { deletedAt: null } },
          include: {
            user: {
              select: {
                id: true,
                username: true,
                displayName: true,
                email: true,
                avatar: true,
                status: true,
              },
            },
          },
        },
        // v2.1: 包含 organization 和区域信息
        organization: {
          include: {
            organizationRegions: {
              include: {
                region: {
                  select: {
                    id: true,
                    code: true,
                    name: true,
                  },
                },
              },
            },
            primaryRegion: {
              select: {
                id: true,
                code: true,
                name: true,
              },
            },
          },
        },
      } as any,
    });

    if (!department) {
      throw new NotFoundException('Department not found');
    }

    // Get head (department manager) info
    let head = null;
    if (department.headId) {
      head = await this.prisma.user.findUnique({
        where: { id: department.headId, deletedAt: null },
        select: {
          id: true,
          displayName: true,
          username: true,
          email: true,
          avatar: true,
          departmentMemberships: {
            where: { departmentId: id },
            include: {
              position: {
                select: { name: true },
              },
            },
          },
        } as any,
      });
    }

    // v2.1: 从 organization 获取区域数据
    const regions = (department as any).organization?.organizationRegions?.map((or: any) => ({
      id: or.region.id,
      code: or.region.code,
      name: or.region.name,
      isDefault: or.isDefault || false,
    })) || [];

    // v2.1: 移除 organization 内部结构，只保留基本信息
    const { organization, ...cleanDepartment } = department as any;

    // 计算员工数量
    const employeeCount = cleanDepartment.userMemberships?.length || 0;

    return {
      ...cleanDepartment,
      head,
      employeeCount,
      organization: {
        id: organization?.id,
        name: organization?.name,
        code: organization?.code,
      },
      regions, // v2.1: 向后兼容
      primaryRegion: organization?.primaryRegion || null, // v2.1: 从 organization 获取
    };
  }

  /**
   * Get department members
   */
  async getMembers(id: string, includeSubDepartments: boolean = false) {
    const department = await this.prisma.department.findUnique({
      where: { id, deletedAt: null },
    });

    if (!department) {
      throw new NotFoundException('Department not found');
    }

    // 获取顶级组织 ID（用于查询用户在该组织下的所有部门）
    let topLevelOrgId = id;
    let currentDept = department;
    while (currentDept.parentId) {
      const parent = await this.prisma.department.findUnique({
        where: { id: currentDept.parentId },
        select: { id: true, parentId: true },
      });
      if (!parent) break;
      topLevelOrgId = parent.id;
      currentDept = parent as any;
    }

    // 获取该组织下的所有部门 ID
    const allOrgDepartmentIds = await this.getAllSubDepartmentIds(topLevelOrgId);
    allOrgDepartmentIds.unshift(topLevelOrgId); // 包含顶级组织本身

    // 获取要查询的部门ID列表（用于过滤显示的成员）
    let departmentIds = [id];
    if (includeSubDepartments) {
      const allSubDepartmentIds = await this.getAllSubDepartmentIds(id);
      departmentIds = [id, ...allSubDepartmentIds];
    }

    const userMemberships = await (this.prisma as any).userDepartment.findMany({
      where: {
        departmentId: { in: departmentIds },
        leftAt: null, // ✅ 修复：只查询仍在职的成员
        user: {
          deletedAt: null,
        },
      },
      include: {
        user: {
          select: {
            id: true,
            username: true,
            displayName: true,
            email: true,
            avatar: true,
            status: true,
            employeeId: true,
            phone: true,
            hiredAt: true,
            source: true,
            createdAt: true,
            updatedAt: true,
          },
        },
        position: {
          select: { id: true, name: true, level: true },
        },
        department: {
          select: { id: true, name: true, code: true },
        },
        manager: {
          select: { id: true, displayName: true, email: true },
        },
      },
      orderBy: { user: { displayName: 'asc' } },
    });

    // 获取用户在当前组织下的所有部门信息
    const userIds = [...new Set(userMemberships.map((um: any) => um.user.id))];
    const allUserDepartments = await (this.prisma as any).userDepartment.findMany({
      where: {
        userId: { in: userIds },
        departmentId: { in: allOrgDepartmentIds },
        leftAt: null,
      },
      include: {
        department: {
          select: { id: true, name: true, code: true },
        },
      },
    });

    // 按用户分组部门信息
    const userDepartmentsMap = new Map<string, any[]>();
    allUserDepartments.forEach((ud: any) => {
      if (!userDepartmentsMap.has(ud.userId)) {
        userDepartmentsMap.set(ud.userId, []);
      }
      userDepartmentsMap.get(ud.userId)!.push({
        id: ud.department.id,
        name: ud.department.name,
        code: ud.department.code,
        isPrimary: ud.isPrimary,
      });
    });

    // Transform to user-centric format
    const userMap = new Map<string, any>();
    
    userMemberships.forEach((ud: any) => {
      const userId = ud.user.id;
      
      // 如果用户已存在，保留主部门的记录
      if (userMap.has(userId)) {
        const existing = userMap.get(userId);
        // 如果当前记录是主部门，替换
        if (ud.isPrimary) {
          userMap.set(userId, {
            ...ud.user,
            position: ud.position,
            department: ud.department,
            manager: ud.manager,
            isPrimary: ud.isPrimary,
            userDepartment: {
              positionId: ud.positionId,
              title: ud.title,
              managerId: ud.managerId,
              joinedAt: ud.joinedAt,
              departmentId: ud.departmentId,
            },
          });
        }
        // 如果现有的不是主部门且当前部门是原始查询的部门，也替换
        else if (!existing.isPrimary && ud.departmentId === id) {
          userMap.set(userId, {
            ...ud.user,
            position: ud.position,
            department: ud.department,
            manager: ud.manager,
            isPrimary: ud.isPrimary,
            userDepartment: {
              positionId: ud.positionId,
              title: ud.title,
              managerId: ud.managerId,
              joinedAt: ud.joinedAt,
              departmentId: ud.departmentId,
            },
          });
        }
      } else {
        userMap.set(userId, {
          ...ud.user,
          position: ud.position,
          department: ud.department,
          manager: ud.manager,
          isPrimary: ud.isPrimary,
          userDepartment: {
            positionId: ud.positionId,
            title: ud.title,
            managerId: ud.managerId,
            joinedAt: ud.joinedAt,
            departmentId: ud.departmentId,
          },
        });
      }
    });

    // 为每个用户附加所有部门信息
    const result = Array.from(userMap.values()).map(user => {
      const allDepartments = userDepartmentsMap.get(user.id) || [];
      return {
        ...user,
        allDepartments, // 添加所有部门列表
      };
    });

    // ✅ 调试：记录 manager 信息
    this.logger.debug(`Returning ${result.length} members for department ${id}`);
    const membersWithManager = result.filter(u => u.manager);
    this.logger.debug(`Members with manager: ${membersWithManager.length}/${result.length}`);
    if (result.length > 0) {
      this.logger.debug('Sample member data:', {
        id: result[0].id,
        displayName: result[0].displayName,
        hasManager: !!result[0].manager,
        manager: result[0].manager,
        userDepartment: result[0].userDepartment,
      });
    }

    return result;
  }

  /**
   * 递归获取所有子部门ID
   */
  private async getAllSubDepartmentIds(departmentId: string): Promise<string[]> {
    const subDepartments = await this.prisma.department.findMany({
      where: {
        parentId: departmentId,
        deletedAt: null,
      },
      select: { id: true },
    });

    if (subDepartments.length === 0) {
      return [];
    }

    const directSubIds = subDepartments.map(d => d.id);
    
    // 递归获取每个子部门的子部门
    const nestedSubIds = await Promise.all(
      directSubIds.map(id => this.getAllSubDepartmentIds(id))
    );

    // 展平数组
    return [...directSubIds, ...nestedSubIds.flat()];
  }

  /**
   * Get department statistics
   */
  async getStats(id: string) {
    const department = await this.prisma.department.findUnique({
      where: { id, deletedAt: null },
    });

    if (!department) {
      throw new NotFoundException('Department not found');
    }

    const [activeUsers, inactiveUsers, childDepartments] = await Promise.all([
      (this.prisma as any).userDepartment.count({
        where: {
          departmentId: id,
          user: {
            deletedAt: null,
            status: 'ACTIVE',
          },
        },
      }),
      (this.prisma as any).userDepartment.count({
        where: {
          departmentId: id,
          user: {
            deletedAt: null,
            status: { not: 'ACTIVE' },
          },
        },
      }),
      this.prisma.department.count({
        where: {
          parentId: id,
          deletedAt: null,
        },
      }),
    ]);

    return {
      activeUsers,
      inactiveUsers,
      totalUsers: activeUsers + inactiveUsers,
      childDepartments,
    };
  }

  /**
   * Update department
   */
  async update(id: string, updateDepartmentDto: UpdateDepartmentDto) {
    const department = await this.prisma.department.findUnique({
      where: { id, deletedAt: null },
    });

    if (!department) {
      throw new NotFoundException('Department not found');
    }

    // 不允许修改部门代码
    if ((updateDepartmentDto as any).code !== undefined) {
      throw new BadRequestException('Department code cannot be modified');
    }

    // Check for circular reference when changing parent
    if (updateDepartmentDto.parentId) {
      if (await this.checkCircularReference(id, updateDepartmentDto.parentId)) {
        throw new BadRequestException('Cannot set department as its own ancestor');
      }

      // Verify parent exists
      const parent = await this.prisma.department.findUnique({
        where: { id: updateDepartmentDto.parentId, deletedAt: null },
      });
      if (!parent) {
        throw new NotFoundException('Parent department not found');
      }
    }

    // Verify head (department manager) exists
    if (updateDepartmentDto.headId) {
      const head = await this.prisma.user.findUnique({
        where: { id: updateDepartmentDto.headId, deletedAt: null },
      });
      if (!head) {
        throw new NotFoundException('Department head not found');
      }
    }

    // v2.1: regionIds 和 defaultRegionId 已废弃，忽略这些字段
    // 区域管理现在在 Organization 层，不在 Department 层
    const { regionIds, defaultRegionId, ...updateData } = updateDepartmentDto;

    // Update department basic info
    const updated = await this.prisma.department.update({
      where: { id },
      data: updateData as any,
      include: {
        parent: {
          select: { id: true, name: true, code: true },
        },
        organization: {
          include: {
            organizationRegions: {
              include: {
                region: {
                  select: { id: true, code: true, name: true },
                },
              },
              orderBy: { isDefault: 'desc' },
            },
          },
        },
      },
    });

    // ✅ 如果更新了负责人，自动将新负责人加入部门
    if (updateDepartmentDto.headId && updateDepartmentDto.headId !== department.headId) {
      try {
        // 检查新负责人是否已经在部门中
        const existingMembership = await this.prisma.userDepartment.findFirst({
          where: {
            userId: updateDepartmentDto.headId,
            departmentId: id,
            leftAt: null,
          },
        });

        // 如果不在，则添加
        if (!existingMembership) {
          await this.prisma.userDepartment.create({
            data: {
              userId: updateDepartmentDto.headId,
              departmentId: id,
              organizationId: department.organizationId, // v2.1: 必填字段
              isPrimary: true, // 设为主部门
              joinedAt: new Date(),
            },
          });
        }
      } catch (error) {
        this.logger.warn(`Failed to add head ${updateDepartmentDto.headId} to department ${id}:`, error);
        // 不阻止部门更新流程，只记录警告
      }
    }

    return {
      ...updated,
      // v2.1: 从 organization 获取区域信息（向后兼容）
      regions: (updated as any).organization?.organizationRegions?.map((or: any) => ({
        ...or.region,
        isDefault: or.isDefault,
      })) || [],
    };
  }

  /**
   * Delete department (soft delete)
   */
  async remove(id: string) {
    const department = await this.prisma.department.findUnique({
      where: { id, deletedAt: null },
      include: {
        userMemberships: { 
          where: { 
            user: { deletedAt: null },
            leftAt: null  // 只检查仍在部门的成员（未设置 leftAt）
          }, 
          include: { user: true } 
        } as any,
        children: { where: { deletedAt: null } },
      } as any,
    });

    if (!department) {
      throw new NotFoundException('Department not found');
    }

    // v2.1.16: 禁止删除根部门 (应用层约束)
    // 根部门的 parentId 为 null
    if (department.parentId === null) {
      throw new BadRequestException(
        'Cannot delete root department. Root department can only be deleted by deleting the organization.'
      );
    }

    if ((department as any).children?.length > 0) {
      throw new IamDepartmentHasChildrenException();
    }

    if ((department as any).userMemberships?.length > 0) {
      throw new IamDepartmentHasUsersException();
    }

    await this.prisma.department.update({
      where: { id },
      data: { deletedAt: new Date() },
    });

    return { message: 'Department deleted successfully' };
  }

  /**
   * Set department head (负责人/主管)
   */
  async setHead(id: string, headId: string) {
    const department = await this.prisma.department.findUnique({
      where: { id, deletedAt: null },
    });

    if (!department) {
      throw new NotFoundException('Department not found');
    }

    const head = await this.prisma.user.findUnique({
      where: { id: headId, deletedAt: null },
    });

    if (!head) {
      throw new NotFoundException('User not found');
    }

    return this.prisma.department.update({
      where: { id },
      data: { headId },
      include: {
        parent: {
          select: { id: true, name: true, code: true },
        },
      },
    });
  }

  /**
   * Remove department head (负责人/主管)
   */
  async removeHead(id: string) {
    const department = await this.prisma.department.findUnique({
      where: { id, deletedAt: null },
    });

    if (!department) {
      throw new NotFoundException('Department not found');
    }

    return this.prisma.department.update({
      where: { id },
      data: { headId: null },
    });
  }

  /**
   * Add single member to department
   */
  async addMember(departmentId: string, dto: AddDepartmentMemberDto) {
    // 验证部门存在
    const department = await this.prisma.department.findUnique({
      where: { id: departmentId, deletedAt: null },
    });

    if (!department) {
      throw new NotFoundException('Department not found');
    }

    // 验证用户存在
    const user = await this.prisma.user.findUnique({
      where: { id: dto.userId, deletedAt: null },
    });

    if (!user) {
      throw new NotFoundException('User not found');
    }

    // 如果设为主部门，需要先将用户的其他主部门取消
    if (dto.isPrimary) {
      await (this.prisma as any).userDepartment.updateMany({
        where: { userId: dto.userId, isPrimary: true },
        data: { isPrimary: false },
      });
    }

    // 创建或更新UserDepartment记录
    const userDepartment = await (this.prisma as any).userDepartment.upsert({
      where: {
        userId_departmentId: {
          userId: dto.userId,
          departmentId,
        },
      },
      update: {
        positionId: dto.positionId,
        managerId: dto.managerId,
        isPrimary: dto.isPrimary || false,
        title: dto.title,
        leftAt: null, // 重新加入时清除离职时间
      },
      create: {
        userId: dto.userId,
        departmentId,
        organizationId: department.organizationId,
        positionId: dto.positionId,
        managerId: dto.managerId,
        isPrimary: dto.isPrimary || false,
        title: dto.title,
      },
      include: {
        user: {
          select: {
            id: true,
            username: true,
            displayName: true,
            email: true,
          },
        },
        department: {
          select: {
            id: true,
            name: true,
            code: true,
          },
        },
        position: {
          select: {
            id: true,
            name: true,
          },
        },
      },
    });

    return userDepartment;
  }

  /**
   * Add multiple members to department (batch)
   */
  async addMembers(departmentId: string, dto: AddDepartmentMembersDto) {
    // 验证部门存在
    const department = await this.prisma.department.findUnique({
      where: { id: departmentId, deletedAt: null },
    });

    if (!department) {
      throw new NotFoundException('Department not found');
    }

    // 验证所有用户存在
    const users = await this.prisma.user.findMany({
      where: {
        id: { in: dto.userIds },
        deletedAt: null,
      },
    });

    if (users.length !== dto.userIds.length) {
      const foundIds = users.map((u) => u.id);
      const missingIds = dto.userIds.filter((id) => !foundIds.includes(id));
      throw new NotFoundException(`Users not found: ${missingIds.join(', ')}`);
    }

    // 批量创建UserDepartment记录
    const results = await Promise.all(
      dto.userIds.map(async (userId) => {
        return this.addMember(departmentId, {
          userId,
          positionId: dto.positionId,
          isPrimary: dto.isPrimary,
        });
      }),
    );

    return {
      message: `Successfully added ${results.length} members to department`,
      count: results.length,
      members: results,
    };
  }

  /**
   * Remove member from department
   */
  async removeMember(departmentId: string, userId: string) {
    // 验证部门和用户存在
    const department = await this.prisma.department.findUnique({
      where: { id: departmentId, deletedAt: null },
    });

    if (!department) {
      throw new NotFoundException('Department not found');
    }

    const user = await this.prisma.user.findUnique({
      where: { id: userId, deletedAt: null },
    });

    if (!user) {
      throw new NotFoundException('User not found');
    }

    // 查找UserDepartment记录
    const userDepartment = await (this.prisma as any).userDepartment.findUnique(
      {
        where: {
          userId_departmentId: {
            userId,
            departmentId,
          },
        },
      },
    );

    if (!userDepartment) {
      throw new NotFoundException(
        'User is not a member of this department',
      );
    }

    // 如果删除的是主部门，自动将另一个部门设为主部门
    let warning: string | undefined;
    if (userDepartment.isPrimary) {
      // 查找用户的其他部门
      const otherDepartments = await (this.prisma as any).userDepartment.findMany({
        where: {
          userId,
          departmentId: { not: departmentId },
          leftAt: null,
        },
        orderBy: { joinedAt: 'asc' },
        take: 1,
      });

      if (otherDepartments.length > 0) {
        // 自动将最早加入的部门设为主部门
        await (this.prisma as any).userDepartment.update({
          where: {
            userId_departmentId: {
              userId,
              departmentId: otherDepartments[0].departmentId,
            },
          },
          data: { isPrimary: true },
        });
        warning = 'Primary department removed. Another department has been automatically set as primary.';
      } else {
        // 这是用户的最后一个部门
        warning = 'Primary department removed. User has no departments now.';
      }
    }

    // 删除UserDepartment记录（或设置leftAt）
    await (this.prisma as any).userDepartment.update({
      where: {
        userId_departmentId: {
          userId,
          departmentId,
        },
      },
      data: {
        leftAt: new Date(),
      },
    });

    return {
      message: 'Member removed successfully',
      warning,
    };
  }
}
