import { Injectable } from "@nestjs/common";
import type { MessageEvent } from "@nestjs/common";
import { Observable } from "rxjs";
import type { OrderUpdateEventPayload } from "@customer-portal/domain/orders";
import { RealtimeService } from "@bff/infra/realtime/realtime.service.js";

/**
 * Order SSE publisher/subscriber adapter.
 *
 * Uses the shared RealtimeService (Redis-backed Pub/Sub) so updates are reliable
 * across multiple BFF instances, while keeping the existing event names stable.
 */
@Injectable()
export class OrderEventsService {
  constructor(private readonly realtime: RealtimeService) {}

  subscribe(orderId: string): Observable<MessageEvent> {
    const topic = this.topic(orderId);
    return this.realtime.subscribe(topic, {
      readyEvent: "order.stream.ready",
      heartbeatEvent: "order.stream.heartbeat",
      heartbeatMs: 30000,
    });
  }

  publish(orderId: string, update: OrderUpdateEventPayload): void {
    this.realtime.publish(this.topic(orderId), "order.update", update);
  }

  private topic(orderId: string): string {
    return `orders:sf:${orderId}`;
  }
}
