import { describe, it, expect, jest, afterEach } from '@jest/globals';
import { createLogger, memoryLogger } from '@4runr/shared';
import { wrapLoggerForMonitoring } from '../middleware/log-capture.js';
import * as monitoring from '../routes/monitoring.js';

describe('wrapLoggerForMonitoring', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });

  it('is idempotent (does not double-wrap)', () => {
    const logger = createLogger('Gateway:Test');
    const once = wrapLoggerForMonitoring(logger);
    const twice = wrapLoggerForMonitoring(once);
    expect(twice).toBe(once);
    expect((twice as any).__monitoringWrapped).toBe(true);
  });

  it('does not wrap memoryLogger (separate buffer)', () => {
    const wrapped = wrapLoggerForMonitoring(memoryLogger);
    expect(wrapped).toBe(memoryLogger);
    expect((wrapped as any).__monitoringWrapped).toBeUndefined();
  });

  it('captures correlationId and component prefix in monitoring buffer', () => {
    const spy = jest.spyOn(monitoring, 'addMonitoringLog');
    const logger = wrapLoggerForMonitoring(createLogger('Gateway'));
    const cid = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
    logger.setCorrelationId(cid);
    logger.info('Handler log line', { runId: 'r1' });

    expect(spy).toHaveBeenCalledWith(
      expect.objectContaining({
        level: 'info',
        message: 'Handler log line',
        context: '4Runr:Gateway',
        correlationId: cid,
        data: { runId: 'r1' },
      })
    );
  });
});
