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

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

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

	const { sessionId: rawSessionId, itemId: rawItemId } = await params;
	const sessionId = rawSessionId.trim();
	const itemId = rawItemId.trim();
	const payload = await req.json().catch(() => ({}));
	const url = new URL(
		`${CLAW_API_URL}/api/sessions/${sessionId}/input-queue/${itemId}`,
	);
	const response = await fetch(url, {
		method: "PATCH",
		cache: "no-store",
		headers: { "content-type": "application/json" },
		body: JSON.stringify({ ...payload, account_id: account.id }),
	});
	const responsePayload = await response.text();
	return new Response(responsePayload, {
		status: response.status,
		headers: {
			"content-type":
				response.headers.get("content-type") ?? "application/json",
		},
	});
}

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

	const { sessionId: rawSessionId, itemId: rawItemId } = await params;
	const sessionId = rawSessionId.trim();
	const itemId = rawItemId.trim();
	const url = new URL(
		`${CLAW_API_URL}/api/sessions/${sessionId}/input-queue/${itemId}`,
	);
	url.searchParams.set("account_id", account.id);
	const response = await fetch(url, { method: "DELETE", cache: "no-store" });
	const responsePayload = await response.text();
	return new Response(responsePayload, {
		status: response.status,
		headers: {
			"content-type":
				response.headers.get("content-type") ?? "application/json",
		},
	});
}
