import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { jwtDecode } from "jwt-decode";
import { SIDE_MENUS, STAFF_ROLE_TYPE } from "./constants";
import { jwt_token_payload } from "./types";

function pathToRegex(path: string) {
  const regexString = "^" + path.replace(/:[^/]+/g, "[^/]+") + "$";
  return new RegExp(regexString);
}

function isTokenExpired(exp?: number) {
  if (!exp) return true;
  return exp * 1000 < Date.now();
}

export function middleware(req: NextRequest) {
  const token = req.cookies.get("accessToken")?.value;
  const { pathname } = req.nextUrl;
  const url = req.nextUrl.clone();

  const isAuthRoute = pathname.startsWith("/login");

  const protectedRoutes = [
    "/dashboard",
    "/doctors",
    "/patients",
    "/staff",
    "/department",
    "/online-case",
    "/transfer-team",
    "/default",
    "/pages",
  ];

  const isProtectedRoute = protectedRoutes.some((path) =>
    pathname.startsWith(path)
  );

  let userRole: string | null = null;
  let isValidToken = false;

  if (token) {
    try {
      const decoded = jwtDecode<jwt_token_payload>(token);

      if (!isTokenExpired(decoded?.exp)) {
        userRole = decoded?.role?.toUpperCase() || null;
        isValidToken = true;
      }
    } catch {
      isValidToken = false;
    }
  }

  // 1️⃣ Protected route بدون توکن معتبر
  if (isProtectedRoute && !isValidToken) {
    const loginUrl = new URL("/login", req.url);
    loginUrl.searchParams.set("returnUrl", pathname);
    return NextResponse.redirect(loginUrl);
  }

  // 2️⃣ چک دسترسی رول
  if (isProtectedRoute && userRole) {
    const isAllowed = SIDE_MENUS.some((menu) => {
      if (menu.href && pathToRegex(menu.href).test(pathname)) {
        return (
          !menu.roles ||
          menu.roles.includes(userRole as STAFF_ROLE_TYPE)
        );
      }

      if (menu.sub?.items) {
        return menu.sub.items.some(
          (item) =>
            item.href &&
            pathToRegex(item.href).test(pathname) &&
            (!item.roles ||
              item.roles.includes(userRole as STAFF_ROLE_TYPE))
        );
      }

      return false;
    });

    if (!isAllowed) {
      return NextResponse.redirect(new URL("/dashboard", req.url));
    }
  }

  // 3️⃣ لاگین شده ولی روی /login است
  if (isAuthRoute && isValidToken) {
    const returnUrl = req.nextUrl.searchParams.get("returnUrl");
    const redirectTo =
      returnUrl && !returnUrl.startsWith("/login")
        ? returnUrl
        : "/dashboard";

    return NextResponse.redirect(new URL(redirectTo, req.url));
  }

  return NextResponse.next();
}
