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";

function sortByNewest<T extends Record<string, unknown>>(rows: T[]) {
  return [...rows].sort((left, right) => {
    const leftTime =
      (typeof left.created_at === "string" && left.created_at) ||
      (typeof left.finished_at === "string" && left.finished_at) ||
      "";
    const rightTime =
      (typeof right.created_at === "string" && right.created_at) ||
      (typeof right.finished_at === "string" && right.finished_at) ||
      "";
    return rightTime.localeCompare(leftTime);
  });
}

function filterByCommandId<T extends Record<string, unknown>>(rows: T[], commandId: string | null) {
  if (!commandId) return rows;
  return rows.filter((row) => row.command_id === commandId);
}

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

    const { client } = await getAuthedConvexClient();
    const context = await buildDocumentBridgeContext({
      request,
      workspaceId,
    });
    const envelope = buildDocumentQueryEnvelope({
      name: "bridge.request.get",
      payload: {
        workspaceId,
        requestId,
        commandId: commandId || null,
      },
    });
    const plan = await resolveRustBridgeQueryPlan({
      context,
      envelope,
    });
    const result = await executeRustBridgeQueryTransport<{
      request_id: string;
      command_logs: Array<Record<string, unknown>>;
      domain_events: Array<Record<string, unknown>>;
      generated_at: string;
    }>({
      client,
      plan,
    });
    const commandLogs = sortByNewest(filterByCommandId(result.command_logs ?? [], commandId || null));
    const domainEvents = sortByNewest(filterByCommandId(result.domain_events ?? [], commandId || null));

    return NextResponse.json({
      request_id: result.request_id,
      command_logs: commandLogs,
      domain_events: domainEvents,
      generated_at: result.generated_at,
      counts: {
        command_logs: commandLogs.length,
        domain_events: domainEvents.length,
      },
      meta: {
        requestId: context.requestId,
        traceId: context.traceId,
        queryName: envelope.name,
        commandId: commandId || null,
      },
    });
  } catch (error) {
    return documentBridgeErrorResponse(error);
  }
}
