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

export interface ProcessedEventEntity {
  id: string;
  eventId: string;
  eventType: string;
  sourceService: string;
  processedAt: Date;
}

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

  /**
   * 查找已处理事件
   */
  async findByEventId(eventId: string): Promise<ProcessedEventEntity | null> {
    const record = await this.prisma.processedEvent.findUnique({
      where: { eventId },
    });
    return record;
  }

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

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

  /**
   * 删除旧的已处理记录（清理）
   * @param before 删除此时间之前的记录
   */
  async deleteOldRecords(before: Date): Promise<number> {
    const result = await this.prisma.processedEvent.deleteMany({
      where: {
        processedAt: { lt: before },
      },
    });
    return result.count;
  }
}
