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

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

export async function POST(req: Request) {
	const account = await getCurrentAccount();
	if (!account)
		return Response.json({ error: "请先登录账号" }, { status: 401 });

	const body = (await req.json().catch(() => ({}))) as {
		session_id?: unknown;
		run_id?: unknown;
	};
	const sessionId =
		typeof body.session_id === "string" ? body.session_id.trim() : "";
	if (!sessionId)
		return Response.json({ error: "Missing session_id" }, { status: 400 });

	const runId = typeof body.run_id === "string" ? body.run_id.trim() : "";
	const response = await fetch(`${CLAW_API_URL}/api/runs/cancel`, {
		method: "POST",
		headers: { "content-type": "application/json" },
		body: JSON.stringify({
			account_id: account.id,
			session_id: sessionId,
			...(runId ? { run_id: runId } : {}),
		}),
	});
	const payload = await response.text();
	return new Response(payload, {
		status: response.status,
		headers: {
			"content-type":
				response.headers.get("content-type") ?? "application/json",
		},
	});
}
