// Generated by bynkc — do not edit by hand.
// Worker entry point for context `hooks`.

import { Ok, Err, type Result, type JsonValue, type BoundaryError, boundaryError, matchPath, httpResultToResponse, verifySignatureHmacSha256 } from "../../runtime.js";
import { compose, type Env } from "./compose.js";
import * as handlers from "./handlers.js";

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    const path = url.pathname;
    const method = request.method;
    const surface = compose(env);
    try {
      if (path.startsWith("/_bynk/call/")) {
        const servicePath = path.slice("/_bynk/call/".length);
        switch (servicePath) {
          default:
            return new Response("Not found", { status: 404 });
        }
      }

      {
        if (method === "POST" && path === "/hooks/event") {
          let __body_json: JsonValue;
          let __raw: string;
          try {
            __raw = await request.text();
          } catch {
            return new Response(JSON.stringify({ kind: "MalformedJson", details: "Invalid request body" }), { status: 400, headers: { "content-type": "application/json" } });
          }
          const __secret = (env as Record<string, unknown>)["WEBHOOK_SECRET"] ?? (globalThis as { process?: { env?: Record<string, unknown> } }).process?.env?.["WEBHOOK_SECRET"];
          if (typeof __secret !== "string") return new Response(null, { status: 401 });
          const __ts = request.headers.get("X-Timestamp");
          if (__ts === null) return new Response(null, { status: 401 });
          const __ok = await verifySignatureHmacSha256(__raw, __secret, request.headers.get("X-Signature"), __ts, 300);
          if (!__ok) return new Response(null, { status: 401 });
          try {
            __body_json = JSON.parse(__raw) as JsonValue;
          } catch {
            return new Response(JSON.stringify({ kind: "MalformedJson", details: "Invalid request body" }), { status: 400, headers: { "content-type": "application/json" } });
          }
          const __r_body = handlers.deserialise_Event(__body_json, "$");
          if (__r_body.tag === "Err") return new Response(JSON.stringify(__r_body.error), { status: 400, headers: { "content-type": "application/json" } });
          const body = __r_body.value;
          const result = await surface.http_POST_hooks_event(body);
          return httpResultToResponse(result, (v: any) => v as JsonValue);
        }
      }
      return new Response("Not Found", { status: 404 });
    } catch {
      return new Response("Internal Server Error", { status: 500 });
    }
  },
};
