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

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

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ name: string }> }
) {
  const { name } = await params;
  try {
    const upstream = await fetch(
      `${CHANNEL_URL}/tasks/agent/${encodeURIComponent(name)}/stream`,
      { headers: { Authorization: `Bearer ${CHANNEL_SECRET}` } }
    );

    if (!upstream.ok || !upstream.body) {
      return NextResponse.json({ error: "Agent task stream unavailable" }, { status: 502 });
    }

    return new Response(upstream.body, {
      headers: {
        "Content-Type": "text/event-stream",
        "Cache-Control": "no-cache",
        Connection: "keep-alive",
        "X-Accel-Buffering": "no",
      },
    });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Unknown error";
    return NextResponse.json({ error: message }, { status: 502 });
  }
}
