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

export const dynamic = "force-dynamic";

export async function GET(request: Request) {
  if (isConvexEnabled()) {
    let auth;
    let client;
    try {
      const authed = await getAuthedConvexClient();
      auth = authed.auth;
      client = authed.client;
    } 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 assetId = searchParams.get("assetId");

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

    const asset = await client.query(api.mediaAssets.getById, { userId: auth.userId, id: assetId });
    if (!asset) {
      return NextResponse.json({ error: "资源不存在" }, { status: 404 });
    }

    const refreshed = await client.mutation(api.mediaAssets.refreshUrl, { userId: auth.userId, id: assetId });
    const signedUrl = (refreshed as { signedUrl?: string | null } | null)?.signedUrl ?? null;
    if (!signedUrl) {
      return NextResponse.json({ error: "生成签名链接失败" }, { status: 500 });
    }

    return NextResponse.json({
      signedUrl: maybeProxyForBrowserUrl(request, signedUrl),
      asset: {
        id: asset.id,
        file_name: asset.file_name,
        mime_type: asset.mime_type,
        file_size: asset.file_size,
        storage_id: (asset as any)?.storage_id ?? null,
        updated_at: (asset as any)?.updated_at ?? null,
      },
    });
  }

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