import { NextRequest } from "next/server";

const CHANNEL_URL = process.env.CHANNEL_URL || "http://127.0.0.1:7100";

export async function GET(request: NextRequest) {
  const conversationId = request.nextUrl.searchParams.get("conversation_id");

  if (!conversationId) {
    return new Response(JSON.stringify({ error: "Missing conversation_id" }), {
      status: 400,
      headers: { "Content-Type": "application/json" },
    });
  }

  // Proxy SSE from the channel server
  const upstream = await fetch(
    `${CHANNEL_URL}/stream?conversation_id=${encodeURIComponent(conversationId)}`,
    { signal: request.signal }
  );

  if (!upstream.ok || !upstream.body) {
    return new Response(JSON.stringify({ error: "Channel server unavailable" }), {
      status: 502,
      headers: { "Content-Type": "application/json" },
    });
  }

  return new Response(upstream.body, {
    headers: {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
      Connection: "keep-alive",
      "X-Accel-Buffering": "no",
    },
  });
}
