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

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

type ModelListRequest = {
	base_url?: string;
	api_key?: string;
};

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

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

async function proxyModelsRequest(
	method: "GET" | "POST",
	payload?: ModelListRequest,
) {
	const account = await getCurrentAccount();
	if (!account) return Response.json({ models: [] }, { status: 401 });

	try {
		const url = new URL(`${CLAW_API_URL}/api/models`);
		if (method === "GET") 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_id: account.id })
				: undefined,
			cache: "no-store",
		});
		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",
				models: [],
			},
			{ status: 502 },
		);
	}
}
