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

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

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

	const body = (await request.json().catch(() => ({}))) as {
		path?: unknown;
		title?: unknown;
		folder_token?: unknown;
	};
	const filePath = typeof body.path === "string" ? body.path.trim() : "";
	if (!filePath) {
		return Response.json({ error: "Missing file path" }, { status: 400 });
	}

	const response = await fetch(`${CLAW_API_URL}/api/files/online-doc`, {
		method: "POST",
		headers: { "content-type": "application/json" },
		body: JSON.stringify({
			account_id: account.id,
			path: filePath,
			...(typeof body.title === "string" && body.title.trim()
				? { title: body.title.trim() }
				: {}),
			...(typeof body.folder_token === "string" && body.folder_token.trim()
				? { folder_token: body.folder_token.trim() }
				: {}),
		}),
		cache: "no-store",
	});
	const payload = await response.text();
	return new Response(payload, {
		status: response.status,
		headers: {
			"content-type":
				response.headers.get("content-type") ?? "application/json",
		},
	});
}
