/**
 * In-memory telemetry event buffer for product backends.
 *
 * Products call createTelemetryBuffer() with an enabled flag,
 * then use trackEvent/getBufferedEvents/flushEvents as needed.
 */

export interface TelemetryEvent {
  event: string;
  userId?: string;
  properties?: Record<string, unknown>;
  timestamp?: string;
}

export interface TelemetryBuffer {
  trackEvent(event: string, userId?: string, properties?: Record<string, unknown>): void;
  getBufferedEvents(): TelemetryEvent[];
  flushEvents(): TelemetryEvent[];
}

export interface TelemetryBufferOptions {
  /** Master switch — when false, trackEvent is a no-op. */
  enabled: boolean;
}

export function createTelemetryBuffer(opts: TelemetryBufferOptions): TelemetryBuffer {
  const buffer: TelemetryEvent[] = [];

  return {
    trackEvent(event: string, userId?: string, properties?: Record<string, unknown>): void {
      if (!opts.enabled) return;
      buffer.push({
        event,
        userId,
        properties,
        timestamp: new Date().toISOString(),
      });
    },

    getBufferedEvents(): TelemetryEvent[] {
      return [...buffer];
    },

    flushEvents(): TelemetryEvent[] {
      const flushed = [...buffer];
      buffer.length = 0;
      return flushed;
    },
  };
}
