// lib/awareness/bus.ts
import {
  AWARENESS_ENABLED,
  AwarenessEventPayload,
  TELEMETRY_ENABLED,
  AwarenessEvent,
} from './events';
import { updateSnapshot, resetSnapshot } from './snapshot';

type AwarenessListener = (event: AwarenessEventPayload) => void;

const listeners: Set<AwarenessListener> = new Set();

// For testing purposes
function _resetListeners(): void {
    listeners.clear();
}

export function resetBus(): void {
    _resetListeners();
    resetSnapshot();
}

export function subscribe(listener: AwarenessListener): () => void {
  listeners.add(listener);
  return () => {
    listeners.delete(listener);
  };
}

export function publish(event: AwarenessEventPayload): void {
  if (!AWARENESS_ENABLED) {
    return;
  }

  if (event.type === AwarenessEvent.TELEMETRY_METRIC && !TELEMETRY_ENABLED) {
    return;
  }

  // Log to console for debugging, respecting the guards
  if (process.env.NODE_ENV !== 'test') {
    console.log('[Awareness]', event.type, event.payload);
  }

  // Update internal state snapshot
  updateSnapshot(event);

  // Notify subscribers
  listeners.forEach(listener => {
    try {
      listener(event);
    } catch (error) {
      console.error('Error in awareness listener:', error);
    }
  });
}
