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

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

type JupyterBindPayload = {
	session_id?: string;
	base_url?: string;
	password?: string;
	workspace_root?: string;
};

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

	const url = new URL(req.url);
	const sessionId = url.searchParams.get("session_id");
	if (!sessionId)
		return Response.json({ error: "缺少 session_id" }, { status: 400 });

	try {
		const target = new URL(`${CLAW_API_URL}/api/jupyter/session`);
		target.searchParams.set("account_id", account.id);
		target.searchParams.set("session_id", sessionId);
		const response = await fetch(target, { 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 },
		);
	}
}

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

	const payload = (await req.json()) as JupyterBindPayload;
	try {
		const response = await fetch(`${CLAW_API_URL}/api/jupyter/bind-session`, {
			method: "POST",
			headers: { "content-type": "application/json" },
			body: JSON.stringify({
				...payload,
				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 },
		);
	}
}
