import { auth } from "@/lib/auth";
import { NextResponse } from "next/server";

export default auth((req) => {
  const { nextUrl } = req;
  const session = req.auth;
  const isLoggedIn = !!session;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const role = (session?.user as any)?.role as string | undefined;

  const isAdminRoute = nextUrl.pathname.startsWith("/admin");
  const isAuthRoute = nextUrl.pathname === "/login";
  const protectedPaths = ["/dashboard", "/my-account", "/checkout"];
  const isProtectedStudentRoute = protectedPaths.some((p) =>
    nextUrl.pathname.startsWith(p)
  );

  // Logged in → redirect away from /login
  if (isAuthRoute && isLoggedIn) {
    const dest =
      role === "SUPER_ADMIN" || role === "ADMIN" ? "/admin" : "/dashboard";
    return NextResponse.redirect(new URL(dest, nextUrl));
  }

  // Admin routes → require ADMIN+
  if (isAdminRoute) {
    if (!isLoggedIn) {
      return NextResponse.redirect(new URL("/login?from=admin", nextUrl));
    }
    if (role !== "SUPER_ADMIN" && role !== "ADMIN") {
      return NextResponse.redirect(new URL("/dashboard", nextUrl));
    }
  }

  // Protected student routes
  if (isProtectedStudentRoute && !isLoggedIn) {
    const cb = encodeURIComponent(nextUrl.pathname);
    return NextResponse.redirect(new URL(`/login?callbackUrl=${cb}`, nextUrl));
  }

  return NextResponse.next();
});

export const config = {
  // Skip static files, images, and the nextauth API itself
  matcher: [
    "/((?!api/auth|_next/static|_next/image|favicon.ico|public|.*\\.png|.*\\.svg|.*\\.ico).*)",
  ],
};
