import { JWT } from "@/utils/jwt";
import { dashboardPages } from "@/config/admin";

export function verifyRoute(request, accessToken) {
  const jwt = new JWT();
  const route = request.nextUrl.pathname;
  const data = jwt.decodeToken(accessToken) || {};
  const routes = flatenRouteList(dashboardPages);

  const currentRoute_ = routes.find((r) => r.route === route);
  const currentRoute = findRoute(route);

  if (!currentRoute) return true;

  const isAuhothorized = currentRoute?.role?.includes(data?.role);
  return isAuhothorized;
}

const flatenRouteList = (routes) => {
  return routes
    .map((route) => [
      route,
      ...(route?.children?.length > 0 ? flatenRouteList(route.children) : []),
    ])
    .flat();
};

const findRoute = (pathname) => {
  const thePath = Array(pathname.split("/").filter((s) => s).length)
    .fill()
    .map(
      (_, index) =>
        `/${pathname
          .split("/")
          .filter((s) => s)
          .slice(0, index + 1)
          .join("/")}`
    );
  const pathlist = [];
  const searchCurrent = (path, pages, depth) => {
    const current = pages.find((page) => {
      if (path[depth] === page.route) {
        pathlist.push(path[depth]);
        return true;
      }

      if (page.children.map((child) => child.route).includes(path[depth])) {
        pathlist.push(page.route, path[depth]);
        return true;
      }
    });

    if (!current) return searchCurrent(path, pages, depth - 1);
    return current;
  };

  const current = searchCurrent(thePath, dashboardPages, thePath.length - 1);
  return current;
};
