import {
  Injectable,
  NotFoundException,
  BadRequestException,
} from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { CreateReviewRuleDto } from './dto/create-review-rule.dto';
import { UpdateReviewRuleDto } from './dto/update-review-rule.dto';

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

  /**
   * 创建评审规则（独立创建，不关联活动）
   */
  async create(
    createReviewRuleDto: CreateReviewRuleDto,
    tenantId?: number,
    creatorId?: number,
  ) {
    if (!tenantId) {
      throw new BadRequestException('租户ID不能为空');
    }

    const data: any = {
      tenantId,
      ruleName: createReviewRuleDto.ruleName,
      ruleDescription: createReviewRuleDto.ruleDescription || null,
      judgeCount: createReviewRuleDto.judgeCount,
      dimensions: JSON.stringify(createReviewRuleDto.dimensions),
      calculationRule: createReviewRuleDto.calculationRule || 'average',
    };

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

    return this.prisma.contestReviewRule.create({
      data,
      include: {
        contests: {
          select: {
            id: true,
            contestName: true,
          },
        },
      },
    });
  }

  /**
   * 根据ID查找评审规则
   */
  async findById(id: number, tenantId?: number) {
    const where: any = { id, validState: 1 };
    if (tenantId) {
      where.tenantId = tenantId;
    }

    const rule = await this.prisma.contestReviewRule.findFirst({
      where,
      include: {
        contests: {
          where: { validState: 1 },
          select: {
            id: true,
            contestName: true,
          },
        },
      },
    });

    if (!rule) {
      throw new NotFoundException('评审规则不存在');
    }

    return rule;
  }

  /**
   * 更新评审规则
   */
  async update(
    id: number,
    updateReviewRuleDto: UpdateReviewRuleDto,
    tenantId?: number,
    modifierId?: number,
  ) {
    // 先验证规则存在
    await this.findById(id, tenantId);

    const data: any = {};

    if (updateReviewRuleDto.ruleName !== undefined) {
      data.ruleName = updateReviewRuleDto.ruleName;
    }
    if (updateReviewRuleDto.ruleDescription !== undefined) {
      data.ruleDescription = updateReviewRuleDto.ruleDescription || null;
    }
    if (updateReviewRuleDto.judgeCount !== undefined) {
      data.judgeCount = updateReviewRuleDto.judgeCount;
    }
    if (updateReviewRuleDto.dimensions !== undefined) {
      data.dimensions = JSON.stringify(updateReviewRuleDto.dimensions);
    }
    if (updateReviewRuleDto.calculationRule !== undefined) {
      data.calculationRule = updateReviewRuleDto.calculationRule;
    }

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

    return this.prisma.contestReviewRule.update({
      where: { id },
      data,
      include: {
        contests: {
          where: { validState: 1 },
          select: {
            id: true,
            contestName: true,
          },
        },
      },
    });
  }

  /**
   * 删除评审规则（软删除）
   */
  async remove(id: number, tenantId?: number) {
    // 先验证规则存在
    const rule = await this.findById(id, tenantId);

    // 检查是否有活动在使用此规则
    const contestsUsingRule = await this.prisma.contest.count({
      where: {
        reviewRuleId: id,
        validState: 1,
      },
    });

    if (contestsUsingRule > 0) {
      throw new NotFoundException(
        `该规则正在被 ${contestsUsingRule} 个活动使用，无法删除`,
      );
    }

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

  /**
   * 分页查询评审规则列表
   */
  async findAll(
    tenantId?: number,
    page: number = 1,
    pageSize: number = 10,
    ruleName?: string,
  ) {
    const skip = (page - 1) * pageSize;
    const where: any = {
      validState: 1,
    };

    if (tenantId) {
      where.tenantId = tenantId;
    }

    if (ruleName) {
      where.ruleName = {
        contains: ruleName,
      };
    }

    const [data, total] = await Promise.all([
      this.prisma.contestReviewRule.findMany({
        where,
        skip,
        take: pageSize,
        include: {
          contests: {
            where: { validState: 1 },
            select: {
              id: true,
              contestName: true,
            },
          },
        },
        orderBy: {
          createTime: 'desc',
        },
      }),
      this.prisma.contestReviewRule.count({ where }),
    ]);

    return {
      list: data,
      total,
      page,
      pageSize,
    };
  }

  /**
   * 获取所有可用的评审规则（用于活动创建时选择）
   */
  async findAllForSelect(tenantId?: number) {
    const where: any = {
      validState: 1,
    };

    if (tenantId) {
      where.tenantId = tenantId;
    }

    return this.prisma.contestReviewRule.findMany({
      where,
      select: {
        id: true,
        ruleName: true,
        ruleDescription: true,
        judgeCount: true,
        calculationRule: true,
      },
      orderBy: {
        createTime: 'desc',
      },
    });
  }
}
