import {
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { CreateNoticeDto } from './dto/create-notice.dto';
import { UpdateNoticeDto } from './dto/update-notice.dto';
import { QueryNoticeDto } from './dto/query-notice.dto';

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

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

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

    const data: any = {
      contestId: createNoticeDto.contestId,
      title: createNoticeDto.title,
      content: createNoticeDto.content,
      noticeType: createNoticeDto.noticeType || 'manual',
      priority: createNoticeDto.priority || 0,
      publishTime: null, // 创建时不自动发布
    };

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

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

  async findAll(contestId: number) {
    return this.prisma.contestNotice.findMany({
      where: {
        contestId,
        validState: 1,
      },
      orderBy: [
        { priority: 'desc' },
        { publishTime: 'desc' },
      ],
      include: {
        contest: {
          select: {
            id: true,
            contestName: true,
          },
        },
      },
    });
  }

  async findAllNotices(queryDto: QueryNoticeDto) {
    const {
      page = 1,
      pageSize = 10,
      title,
      publishDate,
    } = queryDto;

    const where: any = {
      validState: 1,
    };

    // 标题搜索
    if (title) {
      where.title = {
        contains: title,
      };
    }

    // 发布日期搜索
    if (publishDate) {
      const startDate = new Date(publishDate);
      startDate.setHours(0, 0, 0, 0);
      const endDate = new Date(publishDate);
      endDate.setHours(23, 59, 59, 999);
      where.publishTime = {
        gte: startDate,
        lte: endDate,
      };
    }

    const skip = (page - 1) * pageSize;

    const [list, total] = await Promise.all([
      this.prisma.contestNotice.findMany({
        where,
        orderBy: [
          { priority: 'desc' },
          { publishTime: 'desc' },
        ],
        include: {
          contest: {
            select: {
              id: true,
              contestName: true,
            },
          },
        },
        skip,
        take: pageSize,
      }),
      this.prisma.contestNotice.count({ where }),
    ]);

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

  async findOne(id: number) {
    const notice = await this.prisma.contestNotice.findFirst({
      where: {
        id,
        validState: 1,
      },
      include: {
        contest: {
          select: {
            id: true,
            contestName: true,
          },
        },
      },
    });

    if (!notice) {
      throw new NotFoundException('公告不存在');
    }

    return notice;
  }

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

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

    // 处理发布时间
    if (updateNoticeDto.publishTime !== undefined) {
      data.publishTime = updateNoticeDto.publishTime === null ? null : new Date(updateNoticeDto.publishTime);
    }

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

    return this.prisma.contestNotice.update({
      where: { id },
      data,
      include: {
        contest: {
          select: {
            id: true,
            contestName: true,
          },
        },
      },
    });
  }

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

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

