import { Injectable } from '@nestjs/common';
import { Subject } from 'rxjs';

export interface DbChangeEvent {
  timestamp: string;
}

@Injectable()
export class RealtimeEventsService {
  private readonly subject = new Subject<DbChangeEvent>();
  private flushTimer: NodeJS.Timeout | null = null;
  private hasPendingChanges = false;

  readonly events$ = this.subject.asObservable();

  notifyDatabaseWrite(): void {
    this.hasPendingChanges = true;
    if (this.flushTimer) return;

    // Coalesce burst writes into one SSE event to reduce client/server load.
    this.flushTimer = setTimeout(() => {
      this.flushTimer = null;
      if (!this.hasPendingChanges) return;
      this.hasPendingChanges = false;
      this.subject.next({ timestamp: new Date().toISOString() });
    }, 400);
  }
}
