import { NextRequest } from "next/server";

export function getRequestBaseUrl(request: NextRequest) {
  const configured = process.env.APP_URL?.trim();
  if (configured) {
    return new URL(configured);
  }

  const forwardedHost = request.headers.get("x-forwarded-host");
  const forwardedProto = request.headers.get("x-forwarded-proto");
  const host = forwardedHost?.split(",")[0]?.trim() || request.headers.get("host") || request.nextUrl.host;
  const proto = (forwardedProto?.split(",")[0]?.trim() || request.nextUrl.protocol || "http").replace(":", "");

  if (!host) {
    return request.nextUrl;
  }

  return new URL(`${proto}://${host}`);
}
