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

type RouteContext = {
	params: Promise<{ path?: string[] }>;
};

export async function GET(request: Request, context: RouteContext) {
	return proxyAdminRequest(request, context);
}

export async function POST(request: Request, context: RouteContext) {
	return proxyAdminRequest(request, context);
}

export async function PUT(request: Request, context: RouteContext) {
	return proxyAdminRequest(request, context);
}

export async function DELETE(request: Request, context: RouteContext) {
	return proxyAdminRequest(request, context);
}

async function proxyAdminRequest(request: Request, context: RouteContext) {
	const params = await context.params;
	const path = (params.path ?? []).map(encodeURIComponent).join("/");
	const sourceUrl = new URL(request.url);
	const targetUrl = new URL(`${CLAW_API_URL}/api/admin/${path}`);
	for (const [key, value] of sourceUrl.searchParams.entries()) {
		targetUrl.searchParams.set(key, value);
	}

	const init: RequestInit = {
		method: request.method,
		headers: {
			"content-type": request.headers.get("content-type") ?? "application/json",
		},
		cache: "no-store",
	};
	if (!["GET", "HEAD"].includes(request.method)) {
		init.body = await request.text();
	}

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