import { DurableEventBus, EventBus } from '@bytelyst/events';
import { FileQueueStore } from '@bytelyst/queue';
import { config } from './config.js';

// ── Singleton Event Bus ──────────────────────────────────────
// Single instance shared across all modules in platform-service.
// Import this wherever you need to emit or subscribe to events.

export const bus =
  config.EVENT_BUS_BACKEND === 'file'
    ? new DurableEventBus({
        store: new FileQueueStore({ filePath: config.EVENT_BUS_FILE }),
        queueName: 'platform-events',
        pollIntervalMs: config.EVENT_BUS_POLL_MS,
        leaseMs: config.EVENT_BUS_LEASE_MS,
        autoStart: false,
      })
    : new EventBus();

export function startEventBus(): void {
  if (bus instanceof DurableEventBus) {
    bus.start();
  }
}

export async function stopEventBus(): Promise<void> {
  if (bus instanceof DurableEventBus) {
    await bus.stop();
  }
}
