import { describe, expect, it } from "vitest";
import { maybeProxyForBrowserUrl } from "@/lib/url/proxyForBrowser";

const buildReq = () =>
  new Request("https://example.com/api/test", {
    headers: {
      "x-forwarded-proto": "https",
      "x-forwarded-host": "app.example.com",
    },
  });

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

describe("maybeProxyForBrowserUrl", () => {
  it("对 localhost URL 生成 proxy URL", () => {
    const req = buildReq();
    const raw = "http://localhost:3210/api/storage/xxx";
    const out = maybeProxyForBrowserUrl(req, raw);
    const expected = `https://app.example.com/api/onlyoffice/proxy?u=${base64UrlEncodeUtf8(raw)}`;
    expect(out).toBe(expected);
  });

  it("对与 Convex Origin host 匹配的 URL 生成 proxy URL", () => {
    process.env.CONVEX_SELF_HOSTED_URL = "http://backend:3210";
    const req = buildReq();
    const raw = "http://backend:3210/api/storage/yyy";
    const out = maybeProxyForBrowserUrl(req, raw);
    const expected = `https://app.example.com/api/onlyoffice/proxy?u=${base64UrlEncodeUtf8(raw)}`;
    expect(out).toBe(expected);
  });

  it("对外部 URL 不做处理", () => {
    process.env.CONVEX_SELF_HOSTED_URL = "http://backend:3210";
    const req = buildReq();
    const raw = "https://cdn.example.com/image.png";
    const out = maybeProxyForBrowserUrl(req, raw);
    expect(out).toBe(raw);
  });

  it("已经是 /api/onlyoffice/proxy 的 URL 不重复包裹", () => {
    const req = buildReq();
    const raw = "/api/onlyoffice/proxy?u=abc";
    const out = maybeProxyForBrowserUrl(req, raw);
    expect(out).toBe(raw);
  });
});

