export type UnauthorizedDetail = {
  url?: string;
  status?: number;
};

export type UnauthorizedListener = (detail: UnauthorizedDetail) => void;

const listeners = new Set<UnauthorizedListener>();

/**
 * Subscribe to "unauthorized" events emitted by the API layer.
 *
 * Returns an unsubscribe function.
 */
export function onUnauthorized(listener: UnauthorizedListener): () => void {
  listeners.add(listener);
  return () => listeners.delete(listener);
}

/**
 * Emit an "unauthorized" event to all listeners.
 *
 * Intended to be called by the API client when a non-auth endpoint returns 401.
 */
export function emitUnauthorized(detail: UnauthorizedDetail): void {
  for (const listener of listeners) {
    try {
      listener(detail);
    } catch {
      // Never let one listener break other listeners or the caller.
    }
  }
}
