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

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

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

	const incoming = new URL(request.url);
	const sessionId = incoming.searchParams.get("session_id") ?? "";
	const step = incoming.searchParams.get("step") ?? "";
	const runId = incoming.searchParams.get("run_id");
	if (!sessionId || !step) {
		return Response.json(
			{ error: "session_id and step are required" },
			{ status: 400 },
		);
	}

	const url = new URL(`${CLAW_API_URL}/api/training/step-detail`);
	url.searchParams.set("account_id", account.id);
	url.searchParams.set("session_id", sessionId);
	url.searchParams.set("step", step);
	if (runId) url.searchParams.set("run_id", runId);

	const response = await fetch(url, { cache: "no-store" });
	const payload = await response.text();
	return new Response(payload, {
		status: response.status,
		headers: {
			"content-type":
				response.headers.get("content-type") ?? "application/json",
			"cache-control": "no-store",
		},
	});
}
