// src/engine/messaging/SubscriptionBag.ts

export type Unsub = () => void;

export class SubscriptionBag {
  private subs = new Set<Unsub>();
  private disposed = false;

  /**
   * Make SubscriptionBag iterable so we can iterate over unsub functions.
   */
  [Symbol.iterator](): Iterator<Unsub> {
    return this.subs[Symbol.iterator]();
  }

  add(unsub?: Unsub | null): void {
    if (typeof unsub !== 'function') return;
    if (this.disposed) {
      try { unsub(); } catch {}
      return;
    }
    this.subs.add(unsub);
  }

  delete(unsub: Unsub): void {
    this.subs.delete(unsub);
  }

  clear(): void {
    this.subs.clear();
  }

  dispose(): void {
    if (this.disposed) return;
    this.disposed = true;
    for (const u of Array.from(this.subs)) {
      try { u(); } catch {}
    }
    this.subs.clear();
  }
}
