import { Injectable, NotFoundException, BadRequestException, ConflictException } from '@nestjs/common';
import { PrismaService } from '@core/database/prisma/prisma.service';
import { CreatePositionDto, UpdatePositionDto, PositionQueryDto } from './dto/position.dto';

@Injectable()
export class PositionsService {
  constructor(private prisma: PrismaService) {}

  /**
   * Create position
   */
  async create(createPositionDto: CreatePositionDto) {
    const { name, code, level, description } = createPositionDto;

    // Check if code exists
    const existing = await this.prisma.position.findUnique({
      where: { code },
    });

    if (existing) {
      throw new ConflictException({
        statusCode: 409,
        message: '岗位代码已存在',
        error: 'POSITION_CODE_EXISTS',
      });
    }

    return this.prisma.position.create({
      data: {
        name,
        code,
        level: level || 0,
        description,
      },
    });
  }

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

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

    return this.prisma.position.findMany({
      where,
      include: {
        _count: {
          select: {
            userMemberships: { where: { leftAt: null, user: { deletedAt: null } } },
          },
        },
      },
      orderBy: { level: 'asc' },
    });
  }

  /**
   * Find position by ID
   */
  async findOne(id: string) {
    const position = await this.prisma.position.findUnique({
      where: { id, deletedAt: null },
      include: {
        userMemberships: {
          include: {
            user: {
              select: {
                id: true,
                username: true,
                displayName: true,
                email: true,
                status: true,
              },
            },
            department: {
              select: { id: true, name: true },
            },
          },
        },
      },
    });

    if (!position) {
      throw new NotFoundException('Position not found');
    }

    return position;
  }

  /**
   * Update position
   * 注意：不允许修改岗位代码（code）
   */
  async update(id: string, updatePositionDto: UpdatePositionDto) {
    const position = await this.prisma.position.findUnique({
      where: { id, deletedAt: null },
    });

    if (!position) {
      throw new NotFoundException('Position not found');
    }

    // 不允许修改岗位代码
    if ('code' in updatePositionDto) {
      throw new BadRequestException('岗位代码不允许修改');
    }

    return this.prisma.position.update({
      where: { id },
      data: updatePositionDto,
    });
  }

  /**
   * Delete position (soft delete)
   */
  async remove(id: string) {
    const position = await this.prisma.position.findUnique({
      where: { id, deletedAt: null },
      include: {
        _count: {
          select: {
            userMemberships: { where: { leftAt: null, user: { deletedAt: null } } },
          },
        },
      },
    });

    if (!position) {
      throw new NotFoundException('Position not found');
    }

    if (position._count.userMemberships > 0) {
      throw new BadRequestException('该岗位下有用户，无法删除');
    }

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

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