import { jsonError } from "../common.js";

export async function onRequestPost(context: RequestContext) {
  const clonedRequest = context.request.clone();
  const header = (await context.request.text()).split("\n").at(0);

  if (!header) return jsonError("Failed to parse envelope header", 500);

  const { dsn } = JSON.parse(header);

  if (context.env.REMIX_DSN !== dsn) return jsonError("Bad or no DSN", 400);

  const sentryUrl = new URL(dsn);

  const resp = await fetch(
    `https://${sentryUrl.host}/api${sentryUrl.pathname}/envelope/`,
    {
      body: clonedRequest.body,
      headers: {
        "content-type": "application/x-sentry-envelope",
        "x-forwarded-for": context.request.headers.get(
          "cf-connecting-ip",
        ) as string,
      },
      method: "POST",
    },
  );

  return new Response(await resp.text(), {
    headers: {
      "content-type": resp.headers.get("content-type") || "text/plain",
    },
    status: resp.status,
  });
}
