import { describe, it, expect } from 'vitest';
import { createTelemetryBuffer } from './index.js';

describe('createTelemetryBuffer', () => {
  it('buffers events when enabled', () => {
    const buf = createTelemetryBuffer({ enabled: true });
    buf.trackEvent('test.event', 'user-1', { key: 'val' });
    const events = buf.getBufferedEvents();
    expect(events).toHaveLength(1);
    expect(events[0].event).toBe('test.event');
    expect(events[0].userId).toBe('user-1');
    expect(events[0].properties).toEqual({ key: 'val' });
    expect(events[0].timestamp).toBeDefined();
  });

  it('is a no-op when disabled', () => {
    const buf = createTelemetryBuffer({ enabled: false });
    buf.trackEvent('test.event', 'user-1');
    expect(buf.getBufferedEvents()).toHaveLength(0);
  });

  it('flushEvents returns and clears buffer', () => {
    const buf = createTelemetryBuffer({ enabled: true });
    buf.trackEvent('a');
    buf.trackEvent('b');
    const flushed = buf.flushEvents();
    expect(flushed).toHaveLength(2);
    expect(buf.getBufferedEvents()).toHaveLength(0);
  });

  it('getBufferedEvents returns a copy', () => {
    const buf = createTelemetryBuffer({ enabled: true });
    buf.trackEvent('a');
    const copy = buf.getBufferedEvents();
    copy.push({ event: 'fake' });
    expect(buf.getBufferedEvents()).toHaveLength(1);
  });

  it('handles missing optional fields', () => {
    const buf = createTelemetryBuffer({ enabled: true });
    buf.trackEvent('minimal');
    const events = buf.getBufferedEvents();
    expect(events[0].userId).toBeUndefined();
    expect(events[0].properties).toBeUndefined();
  });
});
