import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

const DEFAULT_ORCHESTRATOR_URL = "http://localhost:3001";

function getOrchestratorUrl(): string {
  return (
    process.env.ORCHESTRATOR_URL ??
    process.env.NEXT_PUBLIC_ORCHESTRATOR_URL ??
    process.env.NEXT_PUBLIC_API_URL ??
    DEFAULT_ORCHESTRATOR_URL
  );
}

export async function GET(request: NextRequest): Promise<NextResponse> {
  const orchestratorApiKey = process.env.ORCHESTRATOR_API_KEY;
  if (!orchestratorApiKey) {
    return NextResponse.json(
      { error: "ORCHESTRATOR_API_KEY is not configured on the web server." },
      { status: 503 }
    );
  }

  const limit = request.nextUrl.searchParams.get("limit");
  const query = limit ? `?limit=${encodeURIComponent(limit)}` : "";

  try {
    const response = await fetch(`${getOrchestratorUrl()}/agents/events/recent${query}`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        "X-API-Key": orchestratorApiKey,
      },
      cache: "no-store",
    });

    const text = await response.text();
    return new NextResponse(text, {
      status: response.status,
      headers: {
        "Content-Type": response.headers.get("Content-Type") ?? "application/json",
      },
    });
  } catch {
    return NextResponse.json({ error: "Unable to reach orchestrator." }, { status: 502 });
  }
}
