import { withAuth } from "next-auth/middleware";
import type { NextRequestWithAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";

function isApiPath(pathname: string) {
  return pathname.startsWith("/api/");
}

export default withAuth(
  function middleware(req: NextRequestWithAuth) {
    const { pathname, search } = req.nextUrl;
    const token = req.nextauth.token;

    if (pathname === "/admin/login") {
      return NextResponse.next();
    }

    const isAdminRoute = pathname.startsWith("/admin");
    const isAdminApiRoute = pathname.startsWith("/api/admin");
    const isUsersApiRoute = pathname.startsWith("/api/users");

    const isPublicUsersRegistration = pathname === "/api/users" && req.method === "POST";

    if (isPublicUsersRegistration) {
      return NextResponse.next();
    }

    if (!token) {
      if (isApiPath(pathname)) {
        return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
      }

      const loginUrl = new URL("/admin/login", req.url);
      if (pathname !== "/admin") {
        loginUrl.searchParams.set("callbackUrl", `${pathname}${search}`);
      }
      return NextResponse.redirect(loginUrl);
    }

    const role = String(token.role ?? "USER").toUpperCase();
    const hasAdminAccess = role === "ADMIN" || role === "MODERATOR";

    if ((isAdminRoute || isAdminApiRoute || isUsersApiRoute) && !hasAdminAccess) {
      if (isApiPath(pathname)) {
        return NextResponse.json({ error: "Forbidden" }, { status: 403 });
      }

      return NextResponse.redirect(new URL("/admin/login?error=forbidden", req.url));
    }

    return NextResponse.next();
  },
  {
    callbacks: {
      authorized: () => true,
    },
    pages: {
      signIn: "/admin/login",
    },
  }
);

export const config = {
  matcher: ["/admin/:path*", "/api/admin/:path*", "/api/users/:path*"],
};
