import { getCurrentAccount } from "@/lib/claw-auth";

const CLAW_API_URL = process.env.CLAW_API_URL ?? "http://127.0.0.1:8765";

export const dynamic = "force-dynamic";

export async function GET(request: Request) {
	const account = await getCurrentAccount();
	if (!account) {
		return new Response("unauthorized", { status: 401 });
	}

	const incoming = new URL(request.url);
	const sessionId = incoming.searchParams.get("session_id") ?? "";

	const url = new URL(`${CLAW_API_URL}/api/training/pipeline/stream`);
	url.searchParams.set("account_id", account.id);
	if (sessionId) url.searchParams.set("session_id", sessionId);

	const upstream = await fetch(url, {
		cache: "no-store",
		signal: request.signal,
	});

	if (!upstream.body) {
		return new Response("upstream has no body", { status: 502 });
	}

	return new Response(upstream.body, {
		status: upstream.status,
		headers: {
			"content-type": "text/event-stream",
			"cache-control": "no-store",
			connection: "keep-alive",
			"x-accel-buffering": "no",
		},
	});
}
