import {
  Injectable,
  NotFoundException,
  ConflictException,
} from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { CreateJudgeDto } from './dto/create-judge.dto';
import { UpdateJudgeDto } from './dto/update-judge.dto';

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

  async create(createJudgeDto: CreateJudgeDto, creatorId?: number) {
    // 验证活动是否存在
    const contest = await this.prisma.contest.findUnique({
      where: { id: createJudgeDto.contestId },
    });

    if (!contest) {
      throw new NotFoundException('活动不存在');
    }

    // 验证用户是否存在
    const user = await this.prisma.user.findUnique({
      where: { id: createJudgeDto.judgeId },
    });

    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    // 检查是否已是评委
    const existing = await this.prisma.contestJudge.findFirst({
      where: {
        contestId: createJudgeDto.contestId,
        judgeId: createJudgeDto.judgeId,
        validState: 1,
      },
    });

    if (existing) {
      throw new ConflictException('该用户已是该活动的评委');
    }

    const data: any = {
      contestId: createJudgeDto.contestId,
      judgeId: createJudgeDto.judgeId,
      specialty: createJudgeDto.specialty,
      weight: createJudgeDto.weight,
      description: createJudgeDto.description,
    };

    if (creatorId) {
      data.creator = creatorId;
    }

    return this.prisma.contestJudge.create({
      data,
      include: {
        contest: {
          select: {
            id: true,
            contestName: true,
          },
        },
        judge: {
          select: {
            id: true,
            username: true,
            nickname: true,
            email: true,
            phone: true,
            gender: true,
            status: true,
            tenantId: true,
            tenant: {
              select: {
                id: true,
                name: true,
              },
            },
          },
        },
      },
    });
  }

  async findAll(contestId: number) {
    const judges = await this.prisma.contestJudge.findMany({
      where: {
        contestId,
        validState: 1,
      },
      include: {
        judge: {
          select: {
            id: true,
            username: true,
            nickname: true,
            email: true,
            phone: true,
            gender: true,
            status: true,
            tenantId: true,
            tenant: {
              select: {
                id: true,
                name: true,
              },
            },
            contestJudges: {
              where: {
                validState: 1,
                contest: {
                  validState: 1,
                  status: 'ongoing',
                },
              },
              select: {
                contest: {
                  select: {
                    id: true,
                    contestName: true,
                    status: true,
                  },
                },
              },
            },
          },
        },
      },
      orderBy: {
        createTime: 'desc',
      },
    });

    // 为每个评委添加统计数据
    const judgesWithCounts = await Promise.all(
      judges.map(async (judge) => {
        const [assignedCount, scoredCount] = await Promise.all([
          this.prisma.contestWorkJudgeAssignment.count({
            where: {
              contestId,
              judgeId: judge.judgeId,
            },
          }),
          this.prisma.contestWorkScore.count({
            where: {
              contestId,
              judgeId: judge.judgeId,
              validState: 1,
            },
          }),
        ]);

        return {
          ...judge,
          _count: {
            assignedContestWorks: assignedCount,
            scoredContestWorks: scoredCount,
          },
        };
      }),
    );

    return judgesWithCounts;
  }

  async findOne(id: number) {
    const judge = await this.prisma.contestJudge.findFirst({
      where: {
        id,
        validState: 1,
      },
      include: {
        contest: {
          select: {
            id: true,
            contestName: true,
          },
        },
        judge: {
          select: {
            id: true,
            username: true,
            nickname: true,
            email: true,
            phone: true,
            gender: true,
            status: true,
            tenantId: true,
            tenant: {
              select: {
                id: true,
                name: true,
              },
            },
          },
        },
      },
    });

    if (!judge) {
      throw new NotFoundException('评委记录不存在');
    }

    return judge;
  }

  async update(
    id: number,
    updateJudgeDto: UpdateJudgeDto,
    modifierId?: number,
  ) {
    await this.findOne(id);

    const data: any = { ...updateJudgeDto };

    if (modifierId) {
      data.modifier = modifierId;
    }

    return this.prisma.contestJudge.update({
      where: { id },
      data,
      include: {
        contest: {
          select: {
            id: true,
            contestName: true,
          },
        },
        judge: {
          select: {
            id: true,
            username: true,
            nickname: true,
            email: true,
            phone: true,
            gender: true,
            status: true,
            tenantId: true,
            tenant: {
              select: {
                id: true,
                name: true,
              },
            },
          },
        },
      },
    });
  }

  async remove(id: number) {
    await this.findOne(id);

    // 软删除
    return this.prisma.contestJudge.update({
      where: { id },
      data: {
        validState: 2,
      },
    });
  }
}
