import { NextResponse } from "next/server";
import type { MediaAsset } from "@/types/media";
import { extname } from "path";
import { rewriteToPublicOrigin } from "@/lib/url/rewritePublicOrigin";
import { getMnoteRuntimeConfig } from "@/lib/runtime-config";
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";

const DOC_BUCKET = process.env.NEXT_PUBLIC_SUPABASE_DOC_BUCKET ?? "documents";

const resolveAssetType = (mime: string): "image" | "video" | "audio" | "file" => {
  if (mime.startsWith("image/")) return "image";
  if (mime.startsWith("video/")) return "video";
  if (mime.startsWith("audio/")) return "audio";
  return "file";
};

export async function POST(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 formData = await request.formData();
    const file = formData.get("file");
    const workspaceId = String(formData.get("workspaceId") ?? "");
    const documentId = String(formData.get("documentId") ?? "");
    const mindmapIdRaw = String(formData.get("mindmapId") ?? "").trim();

    if (!(file instanceof File) || !workspaceId || !documentId) {
      return NextResponse.json({ error: "缺少必要参数" }, { status: 400 });
    }

    try {
      const arrayBuffer = await file.arrayBuffer();
      const buffer = Buffer.from(arrayBuffer);
      const assetId =
        typeof crypto.randomUUID === "function"
          ? crypto.randomUUID()
          : `${Date.now()}_${Math.random().toString(16).slice(2)}`;
      const assetType = resolveAssetType(file.type || "");
      const client = await getConvexAuthedHttpClient();

      // 1) 获取 Convex 的上传 URL（短时有效）
      const uploadUrl = await client.mutation(api.mediaAssets.generateUploadUrl, { userId: auth.userId });
      if (!uploadUrl || typeof uploadUrl !== "string") {
        return NextResponse.json({ error: "获取上传地址失败" }, { status: 500 });
      }

      // 2) 上传文件到 Convex Files
      const uploadRes = await fetch(uploadUrl, {
        method: "POST",
        headers: { "Content-Type": file.type || "application/octet-stream" },
        body: buffer,
      });
      if (!uploadRes.ok) {
        const text = await uploadRes.text().catch(() => "");
        return NextResponse.json({ error: `上传到 Convex 失败：${uploadRes.status} ${text}` }, { status: 500 });
      }
      const uploadJson = (await uploadRes.json().catch(() => null)) as { storageId?: string } | null;
      const storageId = uploadJson?.storageId ?? "";
      if (!storageId) {
        return NextResponse.json({ error: "上传到 Convex 失败：缺少 storageId" }, { status: 500 });
      }

      // 3) 写入 Convex 的 media_assets 元数据（并记录 storageId）
      const created = await client.mutation(api.mediaAssets.createWithStorage, {
        userId: auth.userId,
        storageId: storageId as any,
        asset: {
          id: assetId,
          workspace_id: workspaceId,
          document_id: documentId,
          asset_type: assetType,
          file_name: file.name || null,
          file_size: file.size,
          mime_type: file.type || null,
        },
      });

      const asset = created as unknown as MediaAsset;
      const safeAsset = {
        ...(asset as any),
        file_url: maybeProxyForBrowserUrl(request, String((asset as any)?.file_url ?? "")),
        thumbnail_url: maybeProxyForBrowserUrl(request, String((asset as any)?.thumbnail_url ?? (asset as any)?.file_url ?? "")),
      } as MediaAsset;

      return NextResponse.json({
        asset: safeAsset,
        mindmapUrl: `asset:${asset.id}`,
      });
    } catch (error) {
      console.error(error);
      return NextResponse.json({ error: "上传失败" }, { status: 500 });
    }
  }

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

  /*
  const supabase = await createSupabaseRouteClient();
  const {
    data: { session },
  } = await supabase.auth.getSession();

  if (!session) {
    return NextResponse.json({ error: "未登录" }, { status: 401 });
  }

  const formData = await request.formData();
  const file = formData.get("file");
  const workspaceId = String(formData.get("workspaceId") ?? "");
  const documentId = String(formData.get("documentId") ?? "");
  const mindmapIdRaw = String(formData.get("mindmapId") ?? "").trim();

  if (!(file instanceof File) || !workspaceId || !documentId) {
    return NextResponse.json({ error: "缺少必要参数" }, { status: 400 });
  }

  try {
    const arrayBuffer = await file.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer);
    const extension = extname(file.name || "").replace(/\s+/g, "");
    const uniqueId = typeof crypto.randomUUID === "function" ? crypto.randomUUID() : Math.random().toString(36).slice(2);
    // 与 /api/media/batch 的 move/rename 规则对齐：放到 workspaceId/documentId 下
    const mindmapId =
      mindmapIdRaw && /^[a-zA-Z0-9_-]{1,128}$/.test(mindmapIdRaw) ? mindmapIdRaw : "";
    const subdir = mindmapId ? `mindmaps/${mindmapId}` : "";
    const path = `${workspaceId}/${documentId}${subdir ? `/${subdir}` : ""}/${Date.now()}-${uniqueId}${extension}`;
    const assetType = resolveAssetType(file.type || "");

    const { error: uploadError } = await supabase.storage.from(DOC_BUCKET).upload(path, buffer, {
      contentType: file.type,
      upsert: false,
    });

    if (uploadError) {
      return NextResponse.json({ error: uploadError.message }, { status: 500 });
    }

    // 为私有桶生成临时访问链接（7 天）；前端可在需要时通过 /api/media/signed-url 刷新
    // 对于图片，使用高质量参数以获得更好的显示效果
    let signedUrl = "";
    if (assetType === "image") {
      const { data: signed } = await supabase.storage.from(DOC_BUCKET).createSignedUrl(path, 60 * 60 * 24 * 7, {
        transform: {
          quality: 95,  // 高质量
          format: "origin",  // 保持原始格式
        },
      });
      signedUrl = signed?.signedUrl ?? "";
    } else {
      const { data: signed } = await supabase.storage.from(DOC_BUCKET).createSignedUrl(path, 60 * 60 * 24 * 7);
      signedUrl = signed?.signedUrl ?? "";
    }

    signedUrl = rewriteToPublicOrigin(signedUrl, getMnoteRuntimeConfig().supabaseUrl);

    const { data: asset, error } = await supabase
      .from("media_assets")
      .insert({
        workspace_id: workspaceId,
        document_id: documentId,
        file_url: signedUrl,
        thumbnail_url: signedUrl,
        bucket: DOC_BUCKET,
        storage_path: path,
        asset_type: assetType,
        file_name: file.name,
        file_size: file.size,
        mime_type: file.type,
        created_by: session.user.id,
      })
      .select("*")
      .single();

    if (error) {
      return NextResponse.json({ error: error.message }, { status: 500 });
    }

    // 返回 asset 和一个特殊的 asset:id 格式用于存储在思维导图中
    return NextResponse.json({
      asset: asset as MediaAsset,
      mindmapUrl: `asset:${asset.id}`,
    });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: "上传失败" }, { status: 500 });
  }
  */
}
