import { ShadeFileRpcChannel } from '../rpc/channel.js';
import { PendingRpcRegistry } from '../rpc/pending.js';

/**
 * Wire a `PendingRpcRegistry` onto a channel so incoming `response` and
 * `error` envelopes resolve the matching client-side promises.
 *
 * The same channel can serve multiple clients (one per peer); the
 * registry is shared because correlation IDs are globally unique.
 */
export function attachClientRouting(
  channel: ShadeFileRpcChannel,
  pending: PendingRpcRegistry,
): () => void {
  const previous = channel.setHooks({
    onResponse: (_from, env) => pending.resolveResponse(env.envelope),
    onError: (_from, env) => pending.resolveError(env.envelope),
  });
  return () => {
    pending.rejectAll(new Error('client routing detached'));
    channel.setHooks(previous);
  };
}
