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

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

  /**
   * 创建评审规则
   */
  async create(
    createDto: CreateHomeworkReviewRuleDto,
    tenantId: number,
    creatorId?: number,
  ) {
    const data: any = {
      tenantId,
      name: createDto.name,
      description: createDto.description || null,
      criteria: JSON.stringify(createDto.criteria),
    };

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

    return this.prisma.homeworkReviewRule.create({
      data,
      include: {
        homeworks: {
          where: { validState: 1 },
          select: {
            id: true,
            name: true,
          },
        },
      },
    });
  }

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

    const rule = await this.prisma.homeworkReviewRule.findFirst({
      where,
      include: {
        homeworks: {
          where: { validState: 1 },
          select: {
            id: true,
            name: true,
          },
        },
      },
    });

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

    return rule;
  }

  /**
   * 更新评审规则
   */
  async update(
    id: number,
    updateDto: UpdateHomeworkReviewRuleDto,
    tenantId?: number,
    modifierId?: number,
  ) {
    await this.findById(id, tenantId);

    const data: any = {};

    if (updateDto.name !== undefined) {
      data.name = updateDto.name;
    }
    if (updateDto.description !== undefined) {
      data.description = updateDto.description || null;
    }
    if (updateDto.criteria !== undefined) {
      data.criteria = JSON.stringify(updateDto.criteria);
    }

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

    return this.prisma.homeworkReviewRule.update({
      where: { id },
      data,
      include: {
        homeworks: {
          where: { validState: 1 },
          select: {
            id: true,
            name: true,
          },
        },
      },
    });
  }

  /**
   * 删除评审规则（软删除）
   */
  async remove(id: number, tenantId?: number) {
    await this.findById(id, tenantId);

    // 检查是否有作业在使用此规则
    const homeworksUsingRule = await this.prisma.homework.count({
      where: {
        reviewRuleId: id,
        validState: 1,
      },
    });

    if (homeworksUsingRule > 0) {
      throw new BadRequestException(
        `该规则正在被 ${homeworksUsingRule} 个作业使用，无法删除`,
      );
    }

    return this.prisma.homeworkReviewRule.update({
      where: { id },
      data: {
        validState: 2,
      },
    });
  }

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

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

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

    const [data, total] = await Promise.all([
      this.prisma.homeworkReviewRule.findMany({
        where,
        skip,
        take: pageSize,
        include: {
          homeworks: {
            where: { validState: 1 },
            select: {
              id: true,
              name: true,
            },
          },
        },
        orderBy: {
          createTime: 'desc',
        },
      }),
      this.prisma.homeworkReviewRule.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.homeworkReviewRule.findMany({
      where,
      select: {
        id: true,
        name: true,
        description: true,
        criteria: true,
      },
      orderBy: {
        createTime: 'desc',
      },
    });
  }
}
