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 const dynamic = "force-dynamic";

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

  try {
    const upstream = await fetch(`${getOrchestratorUrl()}/api/queue/notifications/stream`, {
      method: "GET",
      headers: {
        "X-API-Key": orchestratorApiKey,
        Accept: "text/event-stream",
      },
      cache: "no-store",
    });

    if (!upstream.ok || upstream.body === null) {
      const message = await upstream.text();
      return new NextResponse(message || "Failed to connect to queue notifications stream", {
        status: upstream.status || 502,
        headers: {
          "Content-Type": upstream.headers.get("Content-Type") ?? "text/plain; charset=utf-8",
        },
      });
    }

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