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

const EVENT_BUS_URL = process.env.EVENT_BUS_URL || "http://127.0.0.1:8089";
const EVENT_BUS_SECRET = process.env.EVENT_BUS_SECRET || "";

export async function GET(req: NextRequest) {
  try {
    const url = new URL(req.url);
    const agent = url.searchParams.get("agent") || undefined;
    const target = agent
      ? `${EVENT_BUS_URL}/subscriptions?agent=${encodeURIComponent(agent)}`
      : `${EVENT_BUS_URL}/subscriptions`;
    const res = await fetch(target);
    const data = await res.json();
    return NextResponse.json(data);
  } catch {
    return NextResponse.json({ error: "Event bus unavailable" }, { status: 503 });
  }
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const res = await fetch(`${EVENT_BUS_URL}/subscribe`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        ...(EVENT_BUS_SECRET ? { Authorization: `Bearer ${EVENT_BUS_SECRET}` } : {}),
      },
      body: JSON.stringify(body),
    });
    const data = await res.json();
    return NextResponse.json(data, { status: res.status });
  } catch {
    return NextResponse.json({ error: "Event bus unavailable" }, { status: 503 });
  }
}
