import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionCookie } from "better-auth/cookies";

// Prefix matches — anything starting with one of these requires auth.
const PROTECTED_PREFIXES = ["/me", "/settings", "/admin"];
// Exact-only match — /la-so (gallery) is protected, but /la-so/<token>
// is a public read-only share view and must NOT require auth.
const PROTECTED_EXACT = ["/la-so"];

// Next.js 16 renamed `middleware` → `proxy`. Same semantics, new export name.
export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // Only check protected dashboard routes — let everything else through.
  // Real session validation happens server-side; this is just a fast cookie gate.
  // Role check (ADMIN) happens in lib/admin-guard.ts on the actual page.
  const isProtected =
    PROTECTED_PREFIXES.some((path) => pathname.startsWith(path)) ||
    PROTECTED_EXACT.includes(pathname);

  if (!isProtected) {
    return NextResponse.next();
  }

  const sessionCookie = getSessionCookie(request);
  if (!sessionCookie) {
    const loginUrl = new URL("/login", request.url);
    loginUrl.searchParams.set("from", pathname);
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/me/:path*", "/la-so", "/settings/:path*", "/admin/:path*"],
};
