import type { GatewayRequest, OutboundMessage } from './protocol.js';
import { makeError, ErrorCode } from './protocol.js';

// A handler function receives a request and a send function for streaming events.
// It returns a final response/error, or void if it already sent a done event.
export type SendFn = (msg: OutboundMessage) => void;
export type HandlerFn = (request: GatewayRequest, send: SendFn) => Promise<OutboundMessage | void>;

export class Router {
  private handlers: Map<string, HandlerFn> = new Map();

  register(method: string, handler: HandlerFn): void {
    this.handlers.set(method, handler);
  }

  async dispatch(request: GatewayRequest, send: SendFn): Promise<OutboundMessage | void> {
    const handler = this.handlers.get(request.method);
    if (!handler) {
      return makeError(request.id, ErrorCode.MethodNotFound, `Unknown method: ${request.method}`);
    }
    return handler(request, send);
  }

  listMethods(): string[] {
    return Array.from(this.handlers.keys());
  }
}
