import { NextResponse } from "next/server";
import { getAuthedConvexClient } from "@/lib/convex/route";
import {
  buildDocumentBridgeContext,
  buildDocumentQueryEnvelope,
  documentBridgeErrorResponse,
} from "@/lib/documents/bridge";
import {
  executeRustBridgeQueryTransport,
  resolveRustBridgeQueryPlan,
} from "@/lib/documents/rust-runtime";

export async function GET(request: Request) {
  try {
    const url = new URL(request.url);
    const workspaceId = url.searchParams.get("workspaceId")?.trim() ?? "";
    if (!workspaceId) {
      return NextResponse.json({ error: "缺少 workspaceId" }, { status: 400 });
    }

    const limit = Number(url.searchParams.get("limit") ?? "50");
    const cursor = url.searchParams.get("cursor")?.trim() ?? "";
    const commandStatus = url.searchParams.get("commandStatus")?.trim() ?? "";
    const eventStatus = url.searchParams.get("eventStatus")?.trim() ?? "";
    const targetPageId = url.searchParams.get("targetPageId")?.trim() ?? "";
    const targetBlockId = url.searchParams.get("targetBlockId")?.trim() ?? "";
    const aggregateType = url.searchParams.get("aggregateType")?.trim() ?? "";
    const aggregateId = url.searchParams.get("aggregateId")?.trim() ?? "";

    const { client } = await getAuthedConvexClient();
    const context = await buildDocumentBridgeContext({
      request,
      workspaceId,
    });
    const envelope = buildDocumentQueryEnvelope({
      name: "bridge.workspace.overview",
      payload: {
        workspaceId,
        limit: Number.isFinite(limit) ? limit : 50,
        cursor: cursor || null,
        commandStatus: commandStatus || null,
        eventStatus: eventStatus || null,
        targetPageId: targetPageId || null,
        targetBlockId: targetBlockId || null,
        aggregateType: aggregateType || null,
        aggregateId: aggregateId || null,
      },
    });
    const plan = await resolveRustBridgeQueryPlan({
      context,
      envelope,
    });
    const result = await executeRustBridgeQueryTransport<{
      workspace_id: string;
      command_logs: Array<Record<string, unknown>>;
      domain_events: Array<Record<string, unknown>>;
      counts: {
        command_logs: number;
        domain_events: number;
      };
      filters: Record<string, unknown> | null;
      next_cursor: string | null;
      has_more: boolean;
      generated_at: string;
    }>({
      client,
      plan,
    });

    return NextResponse.json({
      workspace_id: result.workspace_id,
      command_logs: result.command_logs ?? [],
      domain_events: result.domain_events ?? [],
      counts: result.counts ?? {
        command_logs: Array.isArray(result.command_logs) ? result.command_logs.length : 0,
        domain_events: Array.isArray(result.domain_events) ? result.domain_events.length : 0,
      },
      filters: result.filters ?? null,
      next_cursor: result.next_cursor ?? null,
      has_more: Boolean(result.has_more),
      generated_at: result.generated_at,
      meta: {
        requestId: context.requestId,
        traceId: context.traceId,
        queryName: envelope.name,
      },
    });
  } catch (error) {
    return documentBridgeErrorResponse(error);
  }
}
