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

/**
 * The hub's own login wall (Next "proxy" = the renamed middleware). In production
 * nginx auth_request → /api/authz gates the WHOLE domain (incl. the subpath apps);
 * this guards the hub's own pages and is the wall in local dev. The fine-grained
 * admin checks for the APIs live in their route handlers.
 */
export async function proxy(req: NextRequest) {
  const { pathname } = req.nextUrl;

  if (
    pathname.startsWith("/login") ||
    pathname.startsWith("/api/auth") ||
    pathname.startsWith("/api/authz") ||
    pathname.startsWith("/_next")
  ) {
    return NextResponse.next();
  }

  const user = await verifySessionToken(req.cookies.get(SESSION_COOKIE)?.value);
  if (!user) {
    const url = new URL(withBase("/login"), req.url);
    url.searchParams.set("from", pathname);
    return NextResponse.redirect(url);
  }

  // Admin pages require the admin flag; non-admins are bounced to the cards page.
  if ((pathname === "/admin" || pathname.startsWith("/admin/")) && !user.admin) {
    return NextResponse.redirect(new URL(withBase("/"), req.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|robots.txt).*)"],
};
