const base64UrlEncodeUtf8 = (input: string) => {
  return Buffer.from(input, "utf8")
    .toString("base64")
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/g, "");
};

const getRequestOrigin = (request: Request) => {
  const xfProto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
  const xfHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
  const host = xfHost || request.headers.get("host") || new URL(request.url).host;
  const protocol = (xfProto || new URL(request.url).protocol.replace(/:$/, "")) + ":";
  return `${protocol}//${host}`;
};

const isLocalHostname = (hostname: string) =>
  hostname === "127.0.0.1" ||
  hostname === "localhost" ||
  hostname === "host.docker.internal" ||
  hostname === "0.0.0.0";

const getConvexOriginHost = () => {
  const raw = (process.env.CONVEX_SELF_HOSTED_URL ?? process.env.NEXT_PUBLIC_CONVEX_URL ?? "").trim();
  if (!raw) return null;
  try {
    const u = new URL(raw);
    return u.hostname;
  } catch {
    return null;
  }
};

/**
 * 将“浏览器不可达”的内部回源 URL 包一层 `/api/onlyoffice/proxy?u=...`，避免前端直接请求内网地址。
 * 说明：该函数只做代理 URL 的生成；真正的 SSRF 防护在 `/api/onlyoffice/proxy` 内完成。
 */
export const maybeProxyForBrowserUrl = (request: Request, rawUrl: string) => {
  const input = String(rawUrl || "").trim();
  if (!input) return input;
  if (input.startsWith("/api/onlyoffice/proxy")) return input;

  try {
    const u = new URL(input);
    const convexHost = getConvexOriginHost();
    const shouldProxy = isLocalHostname(u.hostname) || (convexHost ? u.hostname === convexHost : false);
    if (!shouldProxy) return input;

    const origin = getRequestOrigin(request);
    const proxy = new URL("/api/onlyoffice/proxy", origin);
    proxy.searchParams.set("u", base64UrlEncodeUtf8(input));
    return proxy.toString();
  } catch {
    return input;
  }
};

