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

type ClawState = {
	model?: string;
	base_url?: string;
	api_key?: string;
	cwd?: string;
	allow_shell?: boolean;
	allow_write?: boolean;
};

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

export async function GET() {
	return proxyStateRequest("GET");
}

export async function POST(req: Request) {
	const payload = (await req.json()) as ClawState;
	return proxyStateRequest("POST", payload);
}

async function proxyStateRequest(method: "GET" | "POST", payload?: ClawState) {
	try {
		const account = await getCurrentAccount();
		const url = new URL(`${CLAW_API_URL}/api/state`);
		if (method === "GET" && account)
			url.searchParams.set("account_id", account.id);
		const response = await fetch(url, {
			method,
			headers: payload ? { "content-type": "application/json" } : undefined,
			body: payload
				? JSON.stringify({
						...payload,
						...(account ? { account_id: account.id } : {}),
					})
				: undefined,
		});
		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 },
		);
	}
}
