import { type NextRequest, NextResponse } from "next/server";

import { gatewayUrl } from "@/lib/api/gateway";
import { getAccessToken } from "@/lib/auth/session";
import { decodeJwt } from "@/lib/auth/jwt";

/**
 * Forward an admin AI request to the V2 gateway, passing the request body through
 * and returning the gateway's JSON response (status preserved). Admin-gated.
 */
export async function aiProxy(
  req: NextRequest,
  gatewayPath: string,
  method: "GET" | "PUT" | "POST"
): Promise<NextResponse> {
  const token = await getAccessToken();
  if (!token) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const claims = decodeJwt(token);
  const isAdmin =
    String(claims?.is_admin) === "true" ||
    claims?.is_admin === true ||
    String(claims?.is_tenant_admin) === "true";
  if (!isAdmin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  let body: string | undefined;
  if (method !== "GET") {
    const json = await req.json().catch(() => ({}));
    body = JSON.stringify(json);
  }

  const res = await fetch(gatewayUrl(gatewayPath), {
    method,
    cache: "no-store",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body,
  });

  const data = await res.json().catch(() => null);
  if (!res.ok) {
    const message =
      (data && (data.error?.message ?? data.message)) || "Gateway error";
    return NextResponse.json({ error: message }, { status: res.status });
  }
  return NextResponse.json(data ?? {}, { status: 200 });
}
