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

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

type RouteContext = {
	params: Promise<{ skillName: string }>;
};

export async function GET(_request: Request, context: RouteContext) {
	const account = await getCurrentAccount();
	if (!account)
		return Response.json({ error: "unauthorized" }, { status: 401 });
	const { skillName } = await context.params;
	const url = new URL(
		`${CLAW_API_URL}/api/memory/skills/${encodeURIComponent(skillName)}`,
	);
	url.searchParams.set("account_id", account.id);
	const response = await fetch(url, { 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",
		},
	});
}

export async function PUT(request: Request, context: RouteContext) {
	const account = await getCurrentAccount();
	if (!account)
		return Response.json({ error: "unauthorized" }, { status: 401 });
	const { skillName } = await context.params;
	const body = (await request.json()) as { content?: string };
	const response = await fetch(
		`${CLAW_API_URL}/api/memory/skills/${encodeURIComponent(skillName)}`,
		{
			method: "PUT",
			headers: { "content-type": "application/json" },
			body: JSON.stringify({
				account_id: account.id,
				content: body.content ?? "",
			}),
			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",
		},
	});
}
