import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { requireAuthContext } from "@/lib/auth/authContext";
import {
  buildClientToolKey,
  resolveClientToolCall,
  type ClientToolResult,
} from "@/lib/ai-agent/runtime/clientToolBridge";

export const dynamic = "force-dynamic";

type Payload = {
  requestId: string;
  callId: string;
  ok: boolean;
  result?: unknown;
  error?: string;
};

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

  const requestId = String(payload.requestId ?? "").trim();
  const callId = String(payload.callId ?? "").trim();
  if (!requestId || !callId) {
    return NextResponse.json({ error: "缺少 requestId/callId" }, { status: 400 });
  }

  let userId: string | null = null;
  if (isConvexEnabled()) {
    const auth = await requireAuthContext();
    userId = auth.userId;
  }

  const resolvedUserId = async () => {
    if (userId) return userId;
    return null;
  };

  const finalUserId = await resolvedUserId();
  if (!finalUserId) return NextResponse.json({ error: "未登录" }, { status: 401 });

  const result: ClientToolResult = payload.ok
    ? { ok: true, result: "result" in payload ? payload.result : null }
    : { ok: false, error: String(payload.error ?? "客户端工具执行失败") };

  const key = buildClientToolKey(requestId, callId);
  const resolved = resolveClientToolCall({
    key,
    userId: finalUserId,
    result,
  });
  if (!resolved.ok) {
    return NextResponse.json({ error: resolved.error }, { status: 404 });
  }

  return NextResponse.json({ ok: true });
}
