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

/**
 * Route guard (Story 5): unauthenticated users go to /login; authenticated users
 * are kept out of pages their role can't access (RBAC). API auth is covered by
 * the session check; per-endpoint API RBAC is enforced in the UI layer.
 *
 * Next 16 renamed the "middleware" file convention to "proxy".
 */
export async function proxy(req: NextRequest) {
  const { pathname } = req.nextUrl;

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

  const user = await verifySessionToken(req.cookies.get(SESSION_COOKIE)?.value);
  if (!user) {
    // pathname is basePath-stripped; withBase re-applies the prefix on the redirect.
    const url = new URL(withBase("/login"), req.url);
    url.searchParams.set("from", pathname);
    return NextResponse.redirect(url);
  }

  // Role guard for page routes (not /api/*): bounce to the first allowed page.
  if (!pathname.startsWith("/api") && !canAccess(pathname, user.roles)) {
    return NextResponse.redirect(new URL(withBase(firstAllowedPath(user.roles)), req.url));
  }

  return NextResponse.next();
}

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