// middleware.js  (put in project root, same level as pages/ and app/)
import { NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";

export async function middleware(req) {
  const { pathname } = req.nextUrl;

  // Allow these paths always
  const isPublic =
    pathname === "/Login" ||
    pathname.startsWith("/api/auth") ||
    pathname.startsWith("/_next") ||
    pathname === "/favicon.ico";

  if (isPublic) {
    if (pathname === "/Login") {
      const token = await getToken({
        req,
        secret: process.env.NEXTAUTH_SECRET,
      });
      if (token?.role === 1) {
        const url = req.nextUrl.clone();
        url.pathname = "/";
        return NextResponse.redirect(url);
      }
    }
    return NextResponse.next();
  }

  // Protected: only ADMIN (role=1) can access anything else
  const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });

  const isAdmin = token?.role === 1;

  if (!isAdmin) {
    const url = req.nextUrl.clone();
    url.pathname = "/Login";
    return NextResponse.redirect(url);
  }

  return NextResponse.next();
}

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