import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
import { canAccessPath, getDepartmentHomeRoute } from "@/lib/access-control";
import type { DepartmentKey, UserRole } from "@/lib/types";

export default withAuth(
  function middleware(req) {
    const token = req.nextauth.token;
    const role = token?.role as UserRole | undefined;
    const department = (token?.department as DepartmentKey | null | undefined) ?? null;
    const pathname = req.nextUrl.pathname;

    if (!canAccessPath({ role, department }, pathname)) {
      const fallbackPath = role === "owner" ? "/dashboard" : getDepartmentHomeRoute(department);
      const safeFallbackPath = pathname === fallbackPath ? "/settings" : fallbackPath;
      return NextResponse.redirect(new URL(safeFallbackPath, req.url));
    }

    return NextResponse.next();
  },
  {
    pages: {
      signIn: "/login",
    },
  }
);

export const config = {
  matcher: [
    "/dashboard/:path*",
    "/financial-flow/:path*",
    "/experienciometro/:path*",
    "/departments/:path*",
    "/initiatives/:path*",
    "/meetings/:path*",
    "/people/:path*",
    "/data-entry/:path*",
    "/settings/:path*",
    "/api/invitations",
    "/api/experienciometro/:path*",
  ],
};
