import {
  Injectable,
  NotFoundException,
  ConflictException,
} from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { CreateSchoolDto } from './dto/create-school.dto';
import { UpdateSchoolDto } from './dto/update-school.dto';

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

  async create(
    createSchoolDto: CreateSchoolDto,
    tenantId: number,
    creatorId?: number,
  ) {
    // 检查租户是否已有学校信息
    const existingSchool = await this.prisma.school.findUnique({
      where: { tenantId },
    });

    if (existingSchool) {
      throw new ConflictException('该租户已存在学校信息');
    }

    // 检查租户是否存在
    const tenant = await this.prisma.tenant.findUnique({
      where: { id: tenantId },
    });

    if (!tenant) {
      throw new NotFoundException('租户不存在');
    }

    const data: any = {
      ...createSchoolDto,
      tenantId,
    };

    if (createSchoolDto.established) {
      data.established = new Date(createSchoolDto.established);
    }

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

    return this.prisma.school.create({
      data,
      include: {
        tenant: true,
      },
    });
  }

  async findOne(tenantId: number) {
    const school = await this.prisma.school.findUnique({
      where: { tenantId },
      include: {
        tenant: true,
      },
    });

    // 学校信息不存在时返回 null，而不是抛出异常
    // 因为这是一个正常的业务状态（学校信息可能还没有创建）
    return school || null;
  }

  async update(
    tenantId: number,
    updateSchoolDto: UpdateSchoolDto,
    modifierId?: number,
  ) {
    // 验证学校是否存在
    const school = await this.findOne(tenantId);
    if (!school) {
      throw new NotFoundException('学校信息不存在');
    }

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

    if (updateSchoolDto.established) {
      data.established = new Date(updateSchoolDto.established);
    }

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

    return this.prisma.school.update({
      where: { tenantId },
      data,
      include: {
        tenant: true,
      },
    });
  }

  async remove(tenantId: number) {
    // 验证学校是否存在
    const school = await this.findOne(tenantId);
    if (!school) {
      throw new NotFoundException('学校信息不存在');
    }

    return this.prisma.school.delete({
      where: { tenantId },
    });
  }
}
