import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getRequestSession, homeForRole, MEMBER_ROLES } from "@/lib/auth";
import { isStaffSideRole } from "@/lib/auth";

function redirect(req: NextRequest, pathname: string) {
  const url = req.nextUrl.clone();
  url.pathname = pathname;
  url.search = "";
  return NextResponse.redirect(url);
}

export async function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl;
  const session = await getRequestSession(req);

  const isCentral = pathname.startsWith("/central");
  const isPortal = pathname.startsWith("/portal");
  const isMe = pathname.startsWith("/me");
  /// usage guide is for signed-in users only — never public
  const isGuide = pathname === "/guide" || pathname.startsWith("/guide/");
  const isAuthPage = pathname === "/login" || pathname === "/register";

  // Already logged in → land on the home page of the session's role
  if (isAuthPage && session) {
    return redirect(req, homeForRole(session.role));
  }
  if (!session) {
    if (isCentral || isPortal || isMe || isGuide) {
      const url = req.nextUrl.clone();
      url.pathname = "/login";
      url.search = "";
      url.searchParams.set("redirect", pathname);
      return NextResponse.redirect(url);
    }
    return NextResponse.next();
  }

  // Protect central panel — SUPER_ADMIN only
  if (isCentral && session.role !== "SUPER_ADMIN") {
    return redirect(req, homeForRole(session.role));
  }

  // Protect institution portal — INSTITUTION_ADMIN only, except the Student
  // Identity page which admin-assigned maintainers (TEACHER/STAFF logins with
  // an IdentityManager record) may also open; their scope is enforced by the
  // identity APIs themselves.
  const isIdentityPage = pathname === "/portal/identity" || pathname.startsWith("/portal/identity/");
  const identityMaintainer =
    isStaffSideRole(session.role) && isIdentityPage;
  if (isPortal && session.role !== "INSTITUTION_ADMIN" && !identityMaintainer) {
    return redirect(req, homeForRole(session.role));
  }

  // Protect member area — the four member roles only
  if (isMe && !(MEMBER_ROLES as readonly string[]).includes(session.role)) {
    return redirect(req, homeForRole(session.role));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/central/:path*", "/portal/:path*", "/me/:path*", "/guide/:path*", "/guide", "/login", "/register"],
};
