import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { ProcessedEvent } from '@prisma/client';

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

  /**
   * 根据 eventId 查找已处理的事件
   */
  async findByEventId(eventId: string): Promise<ProcessedEvent | null> {
    return this.prisma.processedEvent.findUnique({
      where: { eventId },
    });
  }

  /**
   * 创建已处理事件记录
   */
  async create(data: {
    eventId: string;
    eventType: string;
    sourceService: string;
  }): Promise<ProcessedEvent> {
    return this.prisma.processedEvent.create({
      data: {
        eventId: data.eventId,
        eventType: data.eventType,
        sourceService: data.sourceService,
      },
    });
  }

  /**
   * 删除过期的已处理事件记录（保留24小时）
   */
  async deleteOldEvents(olderThan: Date): Promise<number> {
    const result = await this.prisma.processedEvent.deleteMany({
      where: {
        processedAt: { lt: olderThan },
      },
    });
    return result.count;
  }

  /**
   * 检查事件是否已处理
   */
  async isProcessed(eventId: string): Promise<boolean> {
    const count = await this.prisma.processedEvent.count({
      where: { eventId },
    });
    return count > 0;
  }
}
