import { NextRequest, NextResponse } from "next/server";

function normalizeOrigin(origin: string) {
  return origin.replace(/\/$/, "");
}

function getConfiguredOrigins() {
  return (process.env.ATHENA_PUBLIC_ORIGIN ?? "")
    .split(",")
    .map((origin) => origin.trim())
    .filter(Boolean)
    .map(normalizeOrigin);
}

function getForwardedOrigin(request: NextRequest) {
  const forwardedHost = request.headers.get("x-forwarded-host");

  if (!forwardedHost) {
    return null;
  }

  const forwardedProto = request.headers.get("x-forwarded-proto") ?? "https";
  const firstHost = forwardedHost.split(",")[0]?.trim();
  const firstProto = forwardedProto.split(",")[0]?.trim();

  if (!firstHost || !firstProto) {
    return null;
  }

  return `${firstProto}://${firstHost}`;
}

export function assertSameOrigin(request: NextRequest) {
  const origin = request.headers.get("origin");

  if (!origin) {
    return null;
  }

  const requestOrigins = [
    request.nextUrl.origin,
    getForwardedOrigin(request),
    ...getConfiguredOrigins(),
  ]
    .filter((value): value is string => Boolean(value))
    .map(normalizeOrigin);

  if (!requestOrigins.includes(normalizeOrigin(origin))) {
    return NextResponse.json(
      { detail: "Ungültiger Ursprung der Anfrage" },
      { status: 403 },
    );
  }

  return null;
}
