import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { HttpError, requireAuthContext } from "@/lib/auth/authContext";
import { maybeProxyForBrowserUrl } from "@/lib/url/proxyForBrowser";

export const dynamic = "force-dynamic";

export async function GET(request: Request) {
  if (isConvexEnabled()) {
    try {
      await requireAuthContext();
    } catch (err) {
      if (err instanceof HttpError) {
        return NextResponse.json({ error: "未登录" }, { status: err.status });
      }
      return NextResponse.json({ error: "未登录" }, { status: 401 });
    }

    const { searchParams } = new URL(request.url);
    const fileUrl = searchParams.get("fileUrl");
    if (!fileUrl) {
      return NextResponse.json({ error: "缺少 fileUrl" }, { status: 400 });
    }

    // 说明：Convex + MinIO 模式下，这个接口目前主要用于“外链文件”走 ONLYOFFICE 的场景。
    // 由于外链本身已经是可访问的 URL，这里只做最小透传。
    return NextResponse.json({ signedUrl: maybeProxyForBrowserUrl(request, fileUrl) });
  }

  return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
}
