import { useAuth } from '@/contexts/AuthContext'
import type { CrudAction } from '@/lib/menuKeys'
import type { MenuNode } from '@/types/menu'

function findNode(tree: MenuNode[], key: string): MenuNode | undefined {
  for (const n of tree) {
    if (n.key === key) return n
    const found = findNode(n.children, key)
    if (found) return found
  }
  return undefined
}

export function usePermission() {
  const { menu } = useAuth()
  return {
    can: (menuKey: string, action: CrudAction = 'Read'): boolean => {
      const node = findNode(menu, menuKey)
      if (!node) return false
      return action === 'Read' ? node.canRead
        : action === 'Create' ? node.canCreate
        : action === 'Update' ? node.canUpdate
        : node.canDelete
    },
  }
}
