/**
 * TransportPool - Cache and manage transport connections
 *
 * Limits:
 * - Max 10 concurrent transports
 * - LRU eviction when full
 */

import type { RootEndpoint } from './root_registry';
/** @deprecated Use RootEndpoint */
type RealmEndpoint = RootEndpoint;

export interface PooledTransport {
  endpoint: RootEndpoint;
  transport: any; // Transport interface
  lastUsed: number;
}

export class TransportPool {
  private _pool: Map<string, PooledTransport> = new Map();
  private _maxSize = 10;

  /**
   * Get a transport for a realm, or null if not pooled.
   */
  get(root: string): PooledTransport | null {
    const pooled = this._pool.get(root);
    if (pooled) {
      pooled.lastUsed = Date.now();
      return pooled;
    }
    return null;
  }

  /**
   * Add a transport to the pool.
   * Evicts LRU if at capacity.
   */
  set(root: string, endpoint: RootEndpoint, transport: any): void {
    // Evict if full
    if (this._pool.size >= this._maxSize) {
      this._evictLRU();
    }

    this._pool.set(root, {
      endpoint,
      transport,
      lastUsed: Date.now(),
    });
  }

  /**
   * Remove a transport from the pool.
   */
  remove(root: string): void {
    const pooled = this._pool.get(root);
    if (pooled) {
      // Close transport if it has a close method
      if (pooled.transport.close) {
        pooled.transport.close();
      }
      this._pool.delete(root);
    }
  }

  /**
   * Get pool size.
   */
  get size(): number {
    return this._pool.size;
  }

  /**
   * Clear all pooled transports.
   */
  clear(): void {
    for (const [root] of this._pool) {
      this.remove(root);
    }
  }

  private _evictLRU(): void {
    let oldestRoot: string | null = null;
    let oldestTime = Infinity;

    for (const [root, pooled] of this._pool) {
      if (pooled.lastUsed < oldestTime) {
        oldestTime = pooled.lastUsed;
        oldestRoot = root;
      }
    }

    if (oldestRoot) {
      this.remove(oldestRoot);
    }
  }
}
