import { defineNuxtPlugin } from "nuxt/app";
import { useAuthentication } from "../bridges/authentication.js";
export default defineNuxtPlugin((nuxtApp) => {
  function normalize(input) {
    if (!input) return [];
    if (Array.isArray(input)) return input;
    return [input];
  }
  function isBlank(input) {
    if (!input) return true;
    const arr = normalize(input);
    return arr.length === 0 || arr.every((v) => v.trim() === "");
  }
  const check = (permissionIds) => {
    if (isBlank(permissionIds)) return true;
    const auth = useAuthentication();
    const perms = normalize(permissionIds);
    return perms.some((id) => auth.hasPermission?.(id) ?? false);
  };
  const checkAll = (permissionIds) => {
    if (isBlank(permissionIds)) return true;
    const auth = useAuthentication();
    const perms = normalize(permissionIds);
    return perms.every((id) => auth.hasPermission?.(id) ?? false);
  };
  nuxtApp.vueApp.directive("permission", (el, binding, vnode) => {
    if (!check(binding.value)) {
      vnode?.um?.forEach?.((um) => um());
      el.parentElement?.removeChild(el);
    }
  });
  nuxtApp.vueApp.directive("permission-all", (el, binding, vnode) => {
    if (!checkAll(binding.value)) {
      vnode?.um?.forEach?.((um) => um());
      el.parentElement?.removeChild(el);
    }
  });
  nuxtApp.provide("permission", {
    check,
    checkAll
  });
});
