import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../../database/prisma.service';

@Injectable()
export class NotificationService {
  private readonly logger = new Logger(NotificationService.name);

  constructor(private prisma: PrismaService) {}

  // ==================== 创建通知 ====================

  async createNotification(data: {
    tenantId: number;
    recipientType: 'TEACHER' | 'SCHOOL' | 'PARENT';
    recipientId: number;
    title: string;
    content: string;
    notificationType: 'SYSTEM' | 'TASK' | 'LESSON' | 'GROWTH';
    relatedType?: string;
    relatedId?: number;
  }) {
    const notification = await this.prisma.notification.create({
      data: {
        tenantId: data.tenantId,
        recipientType: data.recipientType,
        recipientId: data.recipientId,
        title: data.title,
        content: data.content,
        notificationType: data.notificationType,
        relatedType: data.relatedType,
        relatedId: data.relatedId,
      },
    });

    this.logger.log(
      `Notification created: ${notification.id} for ${data.recipientType}:${data.recipientId}`
    );

    return notification;
  }

  // 批量创建通知
  async createBatchNotifications(
    notifications: Array<{
      tenantId: number;
      recipientType: 'TEACHER' | 'SCHOOL' | 'PARENT';
      recipientId: number;
      title: string;
      content: string;
      notificationType: 'SYSTEM' | 'TASK' | 'LESSON' | 'GROWTH';
      relatedType?: string;
      relatedId?: number;
    }>
  ) {
    const results = await this.prisma.notification.createMany({
      data: notifications,
    });

    this.logger.log(`Batch notifications created: ${results.count}`);

    return results;
  }

  // ==================== 获取通知 ====================

  async getNotifications(
    tenantId: number,
    recipientType: string,
    recipientId: number,
    query: any
  ) {
    const { page = 1, pageSize = 20, isRead, notificationType } = query;

    const skip = (page - 1) * pageSize;
    const take = +pageSize;

    const where: any = {
      tenantId,
      recipientType,
      recipientId,
    };

    if (isRead !== undefined) {
      where.isRead = isRead === 'true';
    }

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

    const [items, total, unreadCount] = await Promise.all([
      this.prisma.notification.findMany({
        where,
        skip,
        take,
        orderBy: { createdAt: 'desc' },
      }),
      this.prisma.notification.count({ where }),
      this.prisma.notification.count({
        where: { ...where, isRead: false },
      }),
    ]);

    return {
      items,
      total,
      unreadCount,
      page: +page,
      pageSize: +pageSize,
    };
  }

  async getUnreadCount(tenantId: number, recipientType: string, recipientId: number) {
    return this.prisma.notification.count({
      where: {
        tenantId,
        recipientType,
        recipientId,
        isRead: false,
      },
    });
  }

  // ==================== 标记已读 ====================

  async markAsRead(tenantId: number, notificationId: number, recipientType: string, recipientId: number) {
    const notification = await this.prisma.notification.findFirst({
      where: {
        id: notificationId,
        tenantId,
        recipientType,
        recipientId,
      },
    });

    if (!notification) {
      return null;
    }

    return this.prisma.notification.update({
      where: { id: notificationId },
      data: {
        isRead: true,
        readAt: new Date(),
      },
    });
  }

  async markAllAsRead(tenantId: number, recipientType: string, recipientId: number) {
    const result = await this.prisma.notification.updateMany({
      where: {
        tenantId,
        recipientType,
        recipientId,
        isRead: false,
      },
      data: {
        isRead: true,
        readAt: new Date(),
      },
    });

    this.logger.log(
      `Marked ${result.count} notifications as read for ${recipientType}:${recipientId}`
    );

    return result;
  }
}
