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
  );
}

export async function GET(): Promise<Response> {
  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 }
    );
  }

  try {
    const upstream = await fetch(`${getOrchestratorUrl()}/agents/events`, {
      method: "GET",
      headers: {
        "X-API-Key": orchestratorApiKey,
      },
      cache: "no-store",
    });

    if (!upstream.ok || !upstream.body) {
      const text = await upstream.text();
      return new NextResponse(text || "Failed to connect to orchestrator events stream", {
        status: upstream.status || 502,
      });
    }

    return new Response(upstream.body, {
      status: 200,
      headers: {
        "Content-Type": "text/event-stream",
        "Cache-Control": "no-cache, no-transform",
        Connection: "keep-alive",
      },
    });
  } catch {
    return NextResponse.json({ error: "Unable to reach orchestrator." }, { status: 502 });
  }
}
