import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { HttpError } from "@/lib/auth/authContext";
import { documentBridgeErrorResponse } from "@/lib/documents/bridge";
import { executeDocumentSearchQuery } from "@/lib/search/search-query-adapter";
import type { DocumentSearchRequest } from "@/types/search";

export const runtime = "nodejs";

export async function POST(request: Request) {
  try {
    if (!isConvexEnabled()) {
      return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
    }

    const payload = (await request.json()) as DocumentSearchRequest;
    const { response, meta } = await executeDocumentSearchQuery({
      request,
      payload,
    });

    return NextResponse.json(response, {
      headers: {
        "x-request-id": meta.requestId,
        "x-trace-id": meta.traceId,
        "x-query-name": meta.queryName,
      },
    });
  } catch (error) {
    if (error instanceof HttpError) {
      return NextResponse.json({ error: error.message }, { status: error.status });
    }
    return documentBridgeErrorResponse(error);
  }
}
