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

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

type BindBody = {
	session_id?: string;
};

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

	const { workspaceId } = await params;
	const payload = (await req.json()) as BindBody;
	try {
		const target = `${CLAW_API_URL}/api/jupyter/workspaces/${encodeURIComponent(workspaceId)}/bind`;
		const response = await fetch(target, {
			method: "POST",
			headers: { "content-type": "application/json" },
			body: JSON.stringify({
				session_id: payload.session_id,
				account_id: account.id,
			}),
			cache: "no-store",
		});
		const body = await response.text();
		return new Response(body, {
			status: response.status,
			headers: {
				"content-type":
					response.headers.get("content-type") ?? "application/json",
			},
		});
	} catch (err) {
		return Response.json(
			{
				error:
					err instanceof Error
						? `Unable to reach Claw backend: ${err.message}`
						: "Unable to reach Claw backend",
			},
			{ status: 502 },
		);
	}
}
