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

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

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

	const url = new URL(`${CLAW_API_URL}/api/integrations/feishu/status`);
	url.searchParams.set("account_id", account.id);
	const response = await fetch(url, { cache: "no-store" });
	return proxyResponse(response);
}

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 {
		action?: unknown;
	};
	const action = typeof body.action === "string" ? body.action : "login";
	const endpoint =
		action === "logout"
			? "/api/integrations/feishu/logout"
			: "/api/integrations/feishu/login";

	const response = await fetch(`${CLAW_API_URL}${endpoint}`, {
		method: "POST",
		headers: { "content-type": "application/json" },
		body: JSON.stringify({ account_id: account.id }),
		cache: "no-store",
	});
	return proxyResponse(response);
}

async function proxyResponse(response: Response) {
	const payload = await response.text();
	return new Response(payload, {
		status: response.status,
		headers: {
			"content-type":
				response.headers.get("content-type") ?? "application/json",
		},
	});
}
