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

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

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

	const { workspaceId } = await params;
	try {
		const target = new URL(
			`${CLAW_API_URL}/api/jupyter/workspaces/${encodeURIComponent(workspaceId)}`,
		);
		target.searchParams.set("account_id", account.id);
		const response = await fetch(target, {
			method: "DELETE",
			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 },
		);
	}
}
