import {
  createRpcError,
  normalizeThrownError,
  type KdlRpcRequest,
  type KdlRpcResponse,
  type KdlRuntimeHandlers
} from "./rpc.js";

export async function dispatchKdlRpcRequest(
  runtime: KdlRuntimeHandlers,
  request: KdlRpcRequest<unknown[]>
): Promise<KdlRpcResponse> {
  if (!Number.isInteger(request.id)) {
    return {
      id: Number.isFinite(request.id) ? request.id : -1,
      ok: false,
      error: createRpcError("KDL_RPC_INVALID_ID", "RPC request id must be an integer")
    };
  }

  const handler = runtime[request.method];
  if (typeof handler !== "function") {
    return {
      id: request.id,
      ok: false,
      error: createRpcError(
        "KDL_METHOD_NOT_IMPLEMENTED",
        `${String(request.method)} is not implemented by the KDL worker runtime`
      )
    };
  }

  const args = Array.isArray(request.payload) ? request.payload : [request.payload];

  try {
    const result = await handler(...args);
    return {
      id: request.id,
      ok: true,
      result
    };
  } catch (error) {
    return {
      id: request.id,
      ok: false,
      error: normalizeThrownError(error)
    };
  }
}
