import { NextResponse } from "next/server";
import type { MediaAsset } from "@/types/media";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { HttpError, requireAuthContext } from "@/lib/auth/authContext";
import { api } from "@/lib/convex/api";
import { getConvexAuthedHttpClient } from "@/lib/convex/server";
import { maybeProxyForBrowserUrl } from "@/lib/url/proxyForBrowser";

export const dynamic = "force-dynamic";

export async function GET(request: Request) {
  if (isConvexEnabled()) {
    let auth;
    try {
      auth = 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 documentId = searchParams.get("documentId") ?? "";
    const limit = Number.parseInt(searchParams.get("limit") ?? "200", 10);

    if (!documentId) {
      return NextResponse.json({ error: "缺少 documentId" }, { status: 400 });
    }

    const client = await getConvexAuthedHttpClient();
    const items = await client.query(api.mediaAssets.listByDocument, {
      userId: auth.userId,
      documentId,
      limit: Number.isNaN(limit) ? 200 : limit,
    });

    const safeItems = (items ?? []).map((a: any) => ({
      ...a,
      file_url: maybeProxyForBrowserUrl(request, String(a?.file_url ?? "")),
      thumbnail_url: maybeProxyForBrowserUrl(request, String(a?.thumbnail_url ?? a?.file_url ?? "")),
    })) as MediaAsset[];

    return NextResponse.json({ items: safeItems });
  }

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