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

// Auth routes - logged-in users should be redirected away from these
const authRoutes = ["/login", "/signup", "/forgot-password", "/reset-password", "/verify-email"];

// Public routes - accessible to everyone (logged in or not)
const publicRoutes = ["/", "/contact", "/about", "/faq", "/education", "/coming-soon", "/privacy-policy", "/terms-of-service", "/logout", "/user/dashboard", "/user/profiles", "/user/profile"];

// Routes that should NEVER be redirected away from (even if logged in)
const noRedirectRoutes = ["/logout"];

export default auth((req) => {
  const { nextUrl } = req;
  const isLoggedIn = !!req.auth;
  const userRole = (req.auth?.user as any)?.role;

  const isAuthRoute = authRoutes.some(
    (route) => nextUrl.pathname === route || nextUrl.pathname.startsWith(route + "/")
  );

  const isPublicRoute = publicRoutes.some(
    (route) => nextUrl.pathname === route || nextUrl.pathname.startsWith(route + "/")
  );

  const isAgentRoute = nextUrl.pathname.startsWith("/agent");
  const isUserRoute = nextUrl.pathname.startsWith("/user");

  const isApiRoute = nextUrl.pathname.startsWith("/api");
  const isStaticRoute = nextUrl.pathname.startsWith("/_next") ||
                        nextUrl.pathname.startsWith("/assets") ||
                        nextUrl.pathname.includes(".");

  const isNoRedirectRoute = noRedirectRoutes.some(
    (route) => nextUrl.pathname === route || nextUrl.pathname.startsWith(route + "/")
  );

  // Skip middleware for API routes and static files
  if (isApiRoute || isStaticRoute) {
    return NextResponse.next();
  }

  // Never redirect away from no-redirect routes (e.g., /logout must always be accessible)
  if (isNoRedirectRoute) {
    return NextResponse.next();
  }

  // Allow access to public routes for everyone
  if (isPublicRoute) {
    return NextResponse.next();
  }

  // Redirect logged-in users away from auth routes (login, signup, etc.)
  if (isLoggedIn && isAuthRoute) {
    // Redirect to home page instead of dashboard
    return NextResponse.redirect(new URL("/", nextUrl.origin));
  }

  // Redirect non-logged-in users to login page for protected routes
  if (!isLoggedIn && !isAuthRoute) {
    const loginUrl = new URL("/login", nextUrl.origin);
    loginUrl.searchParams.set("callbackUrl", nextUrl.pathname);
    return NextResponse.redirect(loginUrl);
  }

  // Role-based route protection
  if (isLoggedIn) {
    // Block ADMIN and SUPER_ADMIN from web app — they should use admin panel
    if (userRole === "ADMIN" || userRole === "SUPER_ADMIN") {
      // Allow logout and public routes
      if (!isPublicRoute && !isNoRedirectRoute) {
        return NextResponse.redirect(new URL("/logout", nextUrl.origin));
      }
    }

    // Prevent regular users from accessing agent routes
    if (isAgentRoute && userRole !== "AGENT") {
      return NextResponse.redirect(new URL("/user/dashboard", nextUrl.origin));
    }

    // Prevent agents from accessing protected user routes (but allow public user routes)
    if (isUserRoute && userRole === "AGENT" && !isPublicRoute) {
      return NextResponse.redirect(new URL("/agent/dashboard", nextUrl.origin));
    }
  }

  return NextResponse.next();
});

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