export interface HeaderReader {
  get(name: string): string | null;
}

function firstHeaderValue(value: string | null): string | null {
  return value?.split(",", 1)[0]?.trim() || null;
}

function isLocalHost(host: string): boolean {
  return /^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/i.test(host);
}

export function resolvePublicOrigin(headers: HeaderReader): URL {
  const host = firstHeaderValue(headers.get("x-forwarded-host"))
    ?? firstHeaderValue(headers.get("host"))
    ?? "localhost";
  const forwardedProtocol = firstHeaderValue(headers.get("x-forwarded-proto"));
  const protocol = forwardedProtocol === "http" || forwardedProtocol === "https"
    ? forwardedProtocol
    : isLocalHost(host) ? "http" : "https";

  try {
    return new URL(`${protocol}://${host}`);
  } catch {
    return new URL("http://localhost");
  }
}
