import { NextResponse } 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
  );
}

/**
 * Server-side proxy for orchestrator agent status.
 * Keeps ORCHESTRATOR_API_KEY out of browser code.
 */
export async function GET(): 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 controller = new AbortController();
  const timeout = setTimeout(() => {
    controller.abort();
  }, 10_000);

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

    const text = await response.text();
    return new NextResponse(text, {
      status: response.status,
      headers: {
        "Content-Type": response.headers.get("Content-Type") ?? "application/json",
      },
    });
  } catch (error) {
    const message =
      error instanceof Error && error.name === "AbortError"
        ? "Orchestrator request timed out."
        : "Unable to reach orchestrator.";
    return NextResponse.json({ error: message }, { status: 502 });
  } finally {
    clearTimeout(timeout);
  }
}
