import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { join } from 'node:path';
import { tmpdir } from 'node:os';

const ORIGINAL_ENV = { ...process.env };

describe('event bus backend wiring', () => {
  beforeEach(() => {
    vi.resetModules();
    process.env = {
      ...ORIGINAL_ENV,
      COSMOS_ENDPOINT: 'http://localhost:8081',
      COSMOS_KEY: 'test-key',
      JWT_SECRET: 'test-jwt-secret',
    };
  });

  afterEach(async () => {
    vi.resetModules();
    process.env = { ...ORIGINAL_ENV };
  });

  it('uses the durable event bus when configured for file backend', async () => {
    process.env.EVENT_BUS_BACKEND = 'file';
    process.env.EVENT_BUS_FILE = join(tmpdir(), `platform-events-${Date.now()}.json`);

    const [{ DurableEventBus }, eventBusModule] = await Promise.all([
      import('@bytelyst/events'),
      import('./event-bus.js'),
    ]);

    expect(eventBusModule.bus).toBeInstanceOf(DurableEventBus);
    eventBusModule.startEventBus();
    await eventBusModule.stopEventBus();
  });

  it('uses the in-memory event bus when configured for memory backend', async () => {
    process.env.EVENT_BUS_BACKEND = 'memory';

    const [{ EventBus }, eventBusModule] = await Promise.all([
      import('@bytelyst/events'),
      import('./event-bus.js'),
    ]);

    expect(eventBusModule.bus).toBeInstanceOf(EventBus);
  });
});
