import { NextResponse } from "next/server";
import { requireAuthContext } from "@/lib/auth/authContext";
import { getConvexAuthedHttpClient } from "@/lib/convex/server";
import { api } from "@/lib/convex/api";

export const dynamic = "force-dynamic";

type Payload =
  | { type: "document"; documentId: string }
  | { type: "mindmap"; docId: string; mindmapId: string }
  | { type: "media"; assetId: string };

export async function POST(request: Request) {
  const auth = await requireAuthContext();
  const client = await getConvexAuthedHttpClient();

  const body = (await request.json().catch(() => null)) as Payload | null;
  if (!body) {
    return NextResponse.json({ error: "缺少请求体" }, { status: 400 });
  }

  if (body.type === "document") {
    const documentId = String(body.documentId ?? "").trim();
    if (!documentId) return NextResponse.json({ error: "缺少 documentId" }, { status: 400 });
    const result = await client.mutation(api.jobs.enqueueRagIndexDocument, { userId: auth.userId, documentId });
    return NextResponse.json(result);
  }

  if (body.type === "mindmap") {
    const docId = String(body.docId ?? "").trim();
    const mindmapId = String(body.mindmapId ?? "").trim();
    if (!docId) return NextResponse.json({ error: "缺少 docId" }, { status: 400 });
    if (!mindmapId) return NextResponse.json({ error: "缺少 mindmapId" }, { status: 400 });
    const result = await client.mutation(api.jobs.enqueueRagIndexMindmap, { userId: auth.userId, docId, mindmapId });
    return NextResponse.json(result);
  }

  if (body.type === "media") {
    const assetId = String(body.assetId ?? "").trim();
    if (!assetId) return NextResponse.json({ error: "缺少 assetId" }, { status: 400 });
    const result = await client.mutation(api.jobs.enqueueRagIndexMediaAsset, { userId: auth.userId, assetId });
    return NextResponse.json(result);
  }

  return NextResponse.json({ error: "不支持的 type" }, { status: 400 });
}
