import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import { verifySessionToken, SESSION_COOKIE } from "@/lib/session";

/**
 * Server-side proxy to the Symfony backend (Story 5). Injects the shared admin
 * bearer token and the authenticated actor's email so the token never reaches
 * the browser. /api/backend/<x> -> {BACKEND}/api/<x>.
 */
const BACKEND = process.env.BACKEND_INTERNAL_URL || "http://127.0.0.1:8000";
const TOKEN = process.env.ADMIN_API_TOKEN || "";

async function handle(
  req: NextRequest,
  ctx: { params: Promise<{ path: string[] }> },
): Promise<NextResponse> {
  const user = await verifySessionToken((await cookies()).get(SESSION_COOKIE)?.value);
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { path: segments } = await ctx.params;
  const path = (segments || []).join("/");
  const url = `${BACKEND}/api/${path}${req.nextUrl.search}`;

  const headers: Record<string, string> = {
    Authorization: `Bearer ${TOKEN}`,
    "X-Actor-Email": user.email,
  };
  const contentType = req.headers.get("content-type");
  if (contentType) headers["content-type"] = contentType;

  const init: RequestInit = { method: req.method, headers, cache: "no-store" };
  if (!["GET", "HEAD"].includes(req.method)) {
    init.body = await req.text();
  }

  try {
    const resp = await fetch(url, init);
    // Stream the raw bytes so non-JSON responses (e.g. image/webp from the
    // Gallery) pass through intact — reading as text would corrupt binaries.
    const body = await resp.arrayBuffer();
    return new NextResponse(body, {
      status: resp.status,
      headers: {
        "content-type": resp.headers.get("content-type") || "application/json",
      },
    });
  } catch (e) {
    return NextResponse.json(
      { error: `Backend unreachable at ${BACKEND}: ${(e as Error).message}` },
      { status: 502 },
    );
  }
}

export {
  handle as GET,
  handle as POST,
  handle as PUT,
  handle as PATCH,
  handle as DELETE,
};
