import { defineNuxtRouteMiddleware, navigateTo } from "#app";
import { pathToFeatureKey } from "~/utils/workpulse-permissions";

/**
 * Redirect jika user membuka halaman fitur yang tidak diizinkan.
 * Profile & Settings selalu boleh; Employees hanya superadmin (sidebar).
 */
export default defineNuxtRouteMiddleware((to) => {
  if (import.meta.server) return;

  const { isAuthenticated, initAuth } = useAuth();
  initAuth();
  if (!isAuthenticated.value) return;

  const path = to.path.replace(/\/+$/, "") || "/";
  if (path === "/login" || path === "/profile" || path === "/settings") return;

  const key = pathToFeatureKey(path);
  if (!key) {
    if (path === "/employees") {
      const { isSuperadmin } = useWorkpulsePermissions();
      if (!isSuperadmin.value) return navigateTo("/", { replace: true });
    }
    return;
  }

  const { can } = useWorkpulsePermissions();
  if (!can(key)) {
    return navigateTo("/", { replace: true });
  }
});
