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

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

export interface Env {
}

export function compose(env: Env) {
  const deps = {  };
  return {
    async http_POST_ingest(request: Request) {
      let __raw: string;
      try {
        __raw = await request.text();
      } catch {
        return HttpResult.BadRequest("Invalid request body");
      }
      let __who: any = undefined;
      if (__who === undefined) {
        const __authz = request.headers.get("Authorization");
        if (__authz !== null && __authz.startsWith("Bearer ")) {
          const __secret = (env as Record<string, unknown>)["AUTH_JWT_SECRET"] ?? (globalThis as { process?: { env?: Record<string, unknown> } }).process?.env?.["AUTH_JWT_SECRET"];
          if (typeof __secret === "string") {
            const __claims = await verifyBearerJwtHs256(__authz.slice(7), __secret);
            if (__claims.tag === "Ok") {
              const __id = handlers.UserId.of(__claims.value.sub);
              if (__id.tag === "Ok") __who = { tag: "User", identity: __id.value };
            }
          }
        }
      }
      if (__who === undefined) {
        const __secret = (env as Record<string, unknown>)["WH_SECRET"] ?? (globalThis as { process?: { env?: Record<string, unknown> } }).process?.env?.["WH_SECRET"];
        if (typeof __secret === "string") {
          const __sig_ok = await verifySignatureHmacSha256(__raw, __secret, request.headers.get("X-Signature"), null, null);
          if (__sig_ok) __who = { tag: "Hook" };
        }
      }
      if (__who === undefined) return HttpResult.Unauthorized;
      let __body_json: JsonValue;
      try {
        __body_json = JSON.parse(__raw) as JsonValue;
      } catch {
        return HttpResult.BadRequest("Invalid request body");
      }
      const __r_body = handlers.deserialise_Event(__body_json, "$");
      if (__r_body.tag === "Err") return HttpResult.BadRequest("Invalid request body");
      const body = __r_body.value;
      return handlers.api.http_POST_ingest(body, { ...deps, who: __who });
    },
  };
}
