import { getUserPermission } from "@/stores/permissionStore";
import { useStorage } from "@vueuse/core";

export default defineNuxtRouteMiddleware(async (to, from) => {

  let toRoute = useStorage("to_route", to.path);
  const userPermissionStore = getUserPermission();
  // let localStorageToRoute = toRoute.value;
  userPermissionStore.fetchUserPermissions();

  const publicRoutes = ["/403", "/login", from.path];
  if (publicRoutes.includes(to.path)) return true;

  if (
    !userPermissionStore.permissions ||
    !userPermissionStore.permissions.length
  ) {
    try {
      await userPermissionStore.fetchUserPermissions();
    } catch (err) {
      console.error("Error fetching permissions:", err);
      return navigateTo("/403");
    }
  }
  const canAccess = userPermissionStore.hasPagePermission(to.fullPath);

  // console.log("Checking permission for route:", to.fullPath, canAccess);

  if (!canAccess) {
    return navigateTo("/403");
  }

  return true;
});
