import type { Directive } from 'vue'
import { usePermissionStore } from '@/store/modules/permission'

/**
 * 按钮权限指令
 * 用法：v-permission="'sys:user:add'" 或 v-permission="['sys:user:add', 'sys:user:edit']"
 * 无权限时直接移除 DOM 元素
 */
export const vPermission: Directive<HTMLElement, string | string[]> = {
  mounted(el, binding) {
    const permissionStore = usePermissionStore()
    const value = binding.value

    if (!value) return

    const required = Array.isArray(value) ? value : [value]
    const hasAuth = required.some((p) => permissionStore.permissions.includes(p))

    if (!hasAuth) {
      el.parentNode?.removeChild(el)
    }
  },
}

/**
 * 函数式权限判断，用于 JS/TS 逻辑中
 * @param perm - 权限标识，如 'sys:user:add'
 * @returns 是否有该权限
 */
export function hasPerm(perm: string): boolean {
  const permissionStore = usePermissionStore()
  return permissionStore.permissions.includes(perm)
}
