import { Controller, MessageEvent, Sse } from '@nestjs/common';
import { interval, map, merge, Observable } from 'rxjs';
import { RealtimeEventsService } from './realtime-events.service';

@Controller('events')
export class RealtimeController {
  constructor(private readonly realtimeEvents: RealtimeEventsService) {}

  @Sse('stream')
  stream(): Observable<MessageEvent> {
    const changes$ = this.realtimeEvents.events$.pipe(
      map((event) => ({
        type: 'db-change',
        data: event,
      })),
    );

    // Keeps connections alive through proxies and gives clients liveness signal.
    const heartbeat$ = interval(20_000).pipe(
      map(() => ({
        type: 'heartbeat',
        data: { timestamp: new Date().toISOString() },
      })),
    );

    return merge(changes$, heartbeat$);
  }
}
