import { Injectable } from '@nestjs/common';
import { DataSource, Repository } from 'typeorm';
import { ProcessedEvent } from '../../domain/entities/processed-event.entity';

@Injectable()
export class ProcessedEventRepository {
  private readonly repo: Repository<ProcessedEvent>;

  constructor(private readonly dataSource: DataSource) {
    this.repo = this.dataSource.getRepository(ProcessedEvent);
  }

  async hasProcessed(eventId: string): Promise<boolean> {
    const count = await this.repo.count({ where: { eventId } });
    return count > 0;
  }

  async markProcessed(eventId: string, eventType: string): Promise<void> {
    try {
      await this.repo.save(this.repo.create({ eventId, eventType }));
    } catch {
      // Unique constraint violation means it was already processed — safe to ignore
    }
  }
}
