import { Debug } from '../debug';
import { Identity } from './identity';

// Centralizes the analytics consent state so every widget instance stays in sync.
type ConsentListener = (granted: boolean) => void;

let consentGranted = false;
const listeners = new Set<ConsentListener>();

const notifyListeners = (): void => {
  listeners.forEach((listener) => {
    try {
      listener(consentGranted);
    } catch (error) {
      // Listener errors should not block other subscribers.
      Debug.error('Analytics consent listener failed', error instanceof Error ? error : new Error(String(error)));
    }
  });
};

const setAnalyticsConsent = (value: boolean): void => {
  const next = Boolean(value);
  if (consentGranted === next) {
    return;
  }

  consentGranted = next;

  if (consentGranted) {
    Identity.enable();
  } else {
    // Immediately drop identifiers when consent is revoked.
    Identity.clear();
  }

  notifyListeners();
};

const hasAnalyticsConsent = (): boolean => consentGranted;

const subscribeToAnalyticsConsent = (listener: ConsentListener): (() => void) => {
  listeners.add(listener);

  // Emit current value so subscribers can synchronise immediately.
  listener(consentGranted);

  return () => {
    listeners.delete(listener);
  };
};

export const AnalyticsConsent = {
  set: setAnalyticsConsent,
  has: hasAnalyticsConsent,
  subscribe: subscribeToAnalyticsConsent,
};
