/** Process-local invalidations. Connection limits, buffering, and timers belong to consumers. */
export type AccountSelectionEvent = {
  provider: string;
  kind: "oauth" | "api-key";
  revision: number;
};

export type OAuthAccountSelectionSnapshot = Readonly<{
  accountId: string;
  revision?: string;
}>;

export type OAuthAccountRoutingPolicyChange = Readonly<{
  provider: string;
  before: OAuthAccountSelectionSnapshot;
  after: OAuthAccountSelectionSnapshot;
}>;

const listeners = new Set<(event: AccountSelectionEvent) => void>();
const oauthPauseListeners = new Set<(provider: string) => void>();
const oauthRoutingPolicyListeners = new Set<(event: OAuthAccountRoutingPolicyChange) => void>();
let revision = 0;

/** Call only after the authoritative selection has been persisted. */
export function publishAccountSelection(provider: string, kind: AccountSelectionEvent["kind"]): void {
  const event: AccountSelectionEvent = Object.freeze({ provider, kind, revision: ++revision });
  for (const listener of [...listeners]) {
    try {
      listener(event);
    } catch {
      // A disconnected consumer must not turn a committed write into a reported failure.
    }
  }
}

export function subscribeAccountSelections(listener: (event: AccountSelectionEvent) => void): () => void {
  // Give each subscription its own lifetime, even when a callback is reused.
  const subscription = (event: AccountSelectionEvent) => listener(event);
  listeners.add(subscription);
  return () => { listeners.delete(subscription); };
}

/** Internal eligibility invalidation; separate from the public selection stream contract. */
export function publishOAuthAccountPauseChange(provider: string): void {
  for (const listener of [...oauthPauseListeners]) {
    try { listener(provider); } catch { /* A disconnected cache consumer cannot undo persistence. */ }
  }
}

export function subscribeOAuthAccountPauseChanges(listener: (provider: string) => void): () => void {
  const subscription = (provider: string) => listener(provider);
  oauthPauseListeners.add(subscription);
  return () => { oauthPauseListeners.delete(subscription); };
}

/**
 * Internal post-persistence signal for policy-only mutations that advance the
 * selection generation without changing the operator's selected account.
 */
export function publishOAuthAccountRoutingPolicyChange(event: OAuthAccountRoutingPolicyChange): void {
  for (const listener of [...oauthRoutingPolicyListeners]) {
    try { listener(event); } catch { /* A process-local policy observer cannot undo persistence. */ }
  }
}

export function subscribeOAuthAccountRoutingPolicyChanges(listener: (event: OAuthAccountRoutingPolicyChange) => void): () => void {
  const subscription = (event: OAuthAccountRoutingPolicyChange) => listener(event);
  oauthRoutingPolicyListeners.add(subscription);
  return () => { oauthRoutingPolicyListeners.delete(subscription); };
}

export function currentAccountSelectionRevision(): number {
  return revision;
}
