import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  const token = request.cookies.get("refresh_token")?.value;
  const role = request.cookies.get("role")?.value as
    | "candidate"
    | "manager"
    | undefined;

  // --- Public routes that don’t require authentication ---
  const publicPaths = ["/", "/login", "/signup", "/callback"];

  // --- Role-based allowed routes ---
  const roleRoutes: Record<string, string[]> = {
    candidate: ["/candidate/booking", "/candidate/booking/confirmation"],
    manager: ["/manager/dashboard"],
  };

  console.log({ pathname, token, role });

  // === Helper to check if route is public ===
  const isPublic = publicPaths.includes(pathname) || pathname.startsWith("/callback");

  // === 1️⃣ If no token and route is not public → redirect to login ===
  if (!token && !isPublic) {
    console.log("No token found, redirecting to login");
    return NextResponse.redirect(new URL("/login", request.url));
  }

  // === 2️⃣ If user is already authenticated and tries to access public routes → redirect ===
  if (token && ["/login", "/signup"].includes(pathname)) {
    const redirectPath =
      role === "manager" ? "/manager/dashboard" : "/candidate/booking";
    return NextResponse.redirect(new URL(redirectPath, request.url));
  }

  // === 4️⃣ Role-based access control (RBAC) ===
  if (role && roleRoutes[role]) {
    const allowed = roleRoutes[role].some((prefix) =>
      pathname.startsWith(prefix)
    );

    if (!allowed) {
      // Redirect to default route for this role
      const redirectPath =
        role === "manager" ? "/manager/dashboard" : "/candidate/booking";
      return NextResponse.redirect(new URL(redirectPath, request.url));
    }
  }

  // === 5️⃣ Allow request if all checks pass ===
  return NextResponse.next();
}

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};
