// Generated by bynkc — do not edit by hand.
// composition root for `chat` Worker.

import { type ServiceBinding, HttpResult, verifyBearerJwtHs256, serialiseAgentKey } from "../../runtime.js";
import * as handlers from "./handlers.js";

export interface Env {
  ROOM: DurableObjectNamespace;
}

type DurableObjectNamespace = { idFromName(name: string): { toString(): string }; get(id: any): any };

export function compose(env: Env) {
  const deps = { env };
  return {
    async ws_ChatGateway_open(request: Request, roomId: any) {
      if (request.headers.get("Upgrade") !== "websocket") return new Response("Expected a WebSocket upgrade", { status: 426 });
      const __proto = request.headers.get("Sec-WebSocket-Protocol");
      if (__proto === null) return new Response("Unauthorized", { status: 401 });
      const __token = __proto.split(",")[0].trim();
      const __secret = (env as unknown as Record<string, unknown>)["AUTH_SECRET"] ?? (globalThis as { process?: { env?: Record<string, unknown> } }).process?.env?.["AUTH_SECRET"];
      if (typeof __secret !== "string") return new Response("Unauthorized", { status: 401 });
      const __claims = await verifyBearerJwtHs256(__token, __secret);
      if (__claims.tag === "Err") return new Response("Unauthorized", { status: 401 });
      const __id = handlers.UserId.of(__claims.value.sub);
      if (__id.tag === "Err") return new Response("Unauthorized", { status: 401 });
      const __r_roomId = handlers.RoomId.of(roomId);
      if (__r_roomId.tag === "Err") return new Response(JSON.stringify({ kind: "RefinementViolation", path: "param.roomId", violation: __r_roomId.error }), { status: 400, headers: { "content-type": "application/json" } });
      const __ns = deps.env.ROOM;
      const __stub = __ns.get(__ns.idFromName(serialiseAgentKey(__r_roomId.value)));
      const __fwd = new Headers(request.headers);
      __fwd.set("X-Bynk-Ws-Open", JSON.stringify({ args: [__r_roomId.value], identity: __id.value }));
      return __stub.fetch(new Request("https://_bynk/_bynk/ws/open/ChatGateway", { method: request.method, headers: __fwd }));
    },
  };
}
