import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '@core/database/prisma/prisma.service';
import {
  CreateGroupDto,
  UpdateGroupDto,
  QueryGroupDto,
  UpdateGroupMembersDto,
} from '../dto';
import {
  TicketGroupNotFoundException,
  TicketGroupCodeExistsException,
} from '../exceptions';

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

  constructor(private readonly prisma: PrismaService) {}

  /**
   * 创建处理组
   */
  async create(createGroupDto: CreateGroupDto) {
    const { code, ...groupData } = createGroupDto;

    // 检查编码是否已存在
    const existing = await this.prisma.assignmentGroup.findUnique({
      where: { code },
    });
    if (existing) {
      throw new TicketGroupCodeExistsException(code);
    }

    const group = await this.prisma.assignmentGroup.create({
      data: {
        code,
        ...groupData,
      },
    });

    this.logger.log(`处理组创建成功: ${code}`);

    return group;
  }

  /**
   * 获取处理组列表
   */
  async findAll(query: QueryGroupDto) {
    const { isActive, keyword } = query;

    const where: any = {};

    if (isActive !== undefined) {
      where.isActive = isActive;
    }

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

    const groups = await this.prisma.assignmentGroup.findMany({
      where,
      orderBy: { name: 'asc' },
    });

    return groups;
  }

  /**
   * 获取处理组详情
   */
  async findOne(id: string) {
    const group = await this.prisma.assignmentGroup.findUnique({
      where: { id },
    });

    if (!group) {
      throw new TicketGroupNotFoundException(id);
    }

    return group;
  }

  /**
   * 根据编码获取处理组
   */
  async findByCode(code: string) {
    return this.prisma.assignmentGroup.findUnique({
      where: { code },
    });
  }

  /**
   * 更新处理组
   */
  async update(id: string, updateGroupDto: UpdateGroupDto) {
    const group = await this.prisma.assignmentGroup.findUnique({
      where: { id },
    });

    if (!group) {
      throw new TicketGroupNotFoundException(id);
    }

    const updatedGroup = await this.prisma.assignmentGroup.update({
      where: { id },
      data: updateGroupDto,
    });

    this.logger.log(`处理组更新成功: ${updatedGroup.code}`);

    return updatedGroup;
  }

  /**
   * 删除处理组
   */
  async remove(id: string) {
    const group = await this.prisma.assignmentGroup.findUnique({
      where: { id },
    });

    if (!group) {
      throw new TicketGroupNotFoundException(id);
    }

    await this.prisma.assignmentGroup.delete({
      where: { id },
    });

    this.logger.log(`处理组删除成功: ${group.code}`);

    return { success: true };
  }

  /**
   * 添加成员
   */
  async addMembers(id: string, dto: UpdateGroupMembersDto) {
    const group = await this.prisma.assignmentGroup.findUnique({
      where: { id },
    });

    if (!group) {
      throw new TicketGroupNotFoundException(id);
    }

    const newMemberIds = [...new Set([...group.memberIds, ...dto.memberIds])];

    const updatedGroup = await this.prisma.assignmentGroup.update({
      where: { id },
      data: { memberIds: newMemberIds },
    });

    return updatedGroup;
  }

  /**
   * 移除成员
   */
  async removeMembers(id: string, dto: UpdateGroupMembersDto) {
    const group = await this.prisma.assignmentGroup.findUnique({
      where: { id },
    });

    if (!group) {
      throw new TicketGroupNotFoundException(id);
    }

    const newMemberIds = group.memberIds.filter(
      (memberId) => !dto.memberIds.includes(memberId),
    );

    const updatedGroup = await this.prisma.assignmentGroup.update({
      where: { id },
      data: { memberIds: newMemberIds },
    });

    return updatedGroup;
  }

  /**
   * 获取组成员
   */
  async getMembers(id: string) {
    const group = await this.prisma.assignmentGroup.findUnique({
      where: { id },
    });

    if (!group) {
      throw new TicketGroupNotFoundException(id);
    }

    // TODO: 从用户服务获取成员详细信息
    return {
      groupId: id,
      memberIds: group.memberIds,
      members: [], // 需要从用户服务获取
    };
  }

  /**
   * 获取用户所属的处理组
   */
  async getGroupsByUserId(userId: string) {
    const groups = await this.prisma.assignmentGroup.findMany({
      where: {
        memberIds: { has: userId },
        isActive: true,
      },
    });

    return groups;
  }

  /**
   * 获取可用成员（用于分配）
   */
  async getAvailableMembers(groupId: string): Promise<string[]> {
    const group = await this.prisma.assignmentGroup.findUnique({
      where: { id: groupId },
    });

    if (!group || !group.isActive) {
      return [];
    }

    // TODO: 可以加入更多逻辑，如检查成员是否在线、是否休假等
    return group.memberIds;
  }
}
