/**
 * Room subscription manager — tracks active room subscriptions,
 * auto-subscribes on reconnect.
 */
export class RoomSubscriptionManager {
  private subscriptions = new Set<string>();
  private onSubscribe: ((roomId: string) => void) | null = null;
  private onUnsubscribe: ((roomId: string) => void) | null = null;

  /** Register callbacks for subscribe/unsubscribe actions. */
  setCallbacks(
    onSubscribe: (roomId: string) => void,
    onUnsubscribe: (roomId: string) => void,
  ): void {
    this.onSubscribe = onSubscribe;
    this.onUnsubscribe = onUnsubscribe;
  }

  subscribe(roomId: string): void {
    if (this.subscriptions.has(roomId)) return;
    this.subscriptions.add(roomId);
    this.onSubscribe?.(roomId);
  }

  unsubscribe(roomId: string): void {
    if (!this.subscriptions.has(roomId)) return;
    this.subscriptions.delete(roomId);
    this.onUnsubscribe?.(roomId);
  }

  /** Re-subscribe all rooms (used after reconnect). */
  resubscribeAll(): void {
    for (const roomId of this.subscriptions) {
      this.onSubscribe?.(roomId);
    }
  }

  isSubscribed(roomId: string): boolean {
    return this.subscriptions.has(roomId);
  }

  getSubscribedRooms(): string[] {
    return [...this.subscriptions];
  }

  get count(): number {
    return this.subscriptions.size;
  }

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