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(
	req: Request,
	{ params }: { params: Promise<{ sessionId: string }> },
) {
	const account = await getCurrentAccount();
	if (!account)
		return Response.json({ error: "请先登录账号" }, { status: 401 });

	const { sessionId: rawSessionId } = await params;
	const sessionId = rawSessionId.trim();
	const incoming = new URL(req.url);
	const url = new URL(`${CLAW_API_URL}/api/sessions/${sessionId}/state`);
	url.searchParams.set("account_id", account.id);
	for (const key of ["after_message_seq", "after_event_seq"]) {
		const value = incoming.searchParams.get(key);
		if (value) url.searchParams.set(key, value);
	}
	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",
		},
	});
}
