// src/boot/permissions.ts
import { boot } from 'quasar/wrappers';
import { useAuthStore } from 'src/stores/useAuthStore';
import { DirectiveBinding } from 'vue';

export const MenuMapping = {
  home: null,
  app: null,
  version: null,
  user: 'user',
  role: 'role',
  domain: null,
  userDomain: null,
};

export const Actions = {
  user: {
    show: 'user_list',
    add: 'user_add',
    edit: 'user_edit',
    delete: 'user_delete',
  },
  role: {
    show: 'role_list',
  },
  domain: {
    show: 'domain_list',
    add: 'domain_add',
    edit: 'domain_edit',
    delete: 'domain_delete',
    grantUse: {
      list: 'domain_grant_use_list',
      edit: 'domain_grant_use_edit',
    },
    grantManage: {
      list: 'domain_grant_manage_list',
      edit: 'domain_grant_manage_edit',
    },
  },
};

const store = useAuthStore();

export default boot(({ app }) => {
  app.directive('permissions', {
    mounted(el: HTMLElement, binding: DirectiveBinding) {
      if (!hasPermission(binding.value)) {
        hideElement(el);
      }
  },
  });

  app.config.globalProperties.$hasPermission = hasPermission;
});

function hasPermission(value: any) {
  if (!value || store.isSuperAdmin) {
    return true;
  }
  if (typeof value === 'string') {
    return store.permissions[value];
  } else if (typeof value === 'object') {
    return Object.values(value).some((permission: any) => store.permissions[permission]);
  } else if (Array.isArray(value)) {
    return value.some((permission) => store.permissions[permission]);
  }
}

function hideElement(el: HTMLElement) {
  if (el.parentNode) {
    el.parentNode.removeChild(el);
  } else {
    el.style.display = 'none';
  }
}