import type { Permission, RoleAccess } from '~/models/role'

/**
 * Check if user has access to a page
 */
export function useRBAC() {
  // NOTE: this roles was dummy for testing only, it should taken from the user store
  const authStore = useUserStore()

  const checkRole = (roleAccess: RoleAccess, _userRoles?: string[]): boolean => {
    const roles = authStore.userRole
    return roles.some((role: string) => role in roleAccess)
  }

  const checkPermission = (roleAccess: RoleAccess, permission: Permission, _userRoles?: string[]): boolean => {
    const roles = authStore.userRole
    // const roles = ['admisi']
    return roles.some((role: string) => roleAccess[role]?.includes(permission))
  }

  const getUserPermissions = (roleAccess: RoleAccess, _userRoles?: string[]): Permission[] => {
    const roles = authStore.userRole
    // const roles = ['admisi']
    const permissions = new Set<Permission>()

    roles.forEach((role) => {
      if (roleAccess[role]) {
        roleAccess[role].forEach((permission) => permissions.add(permission))
      }
    })

    return Array.from(permissions)
  }

  const hasCreateAccess = (roleAccess: RoleAccess) => checkPermission(roleAccess, 'C')
  const hasReadAccess = (roleAccess: RoleAccess) => checkPermission(roleAccess, 'R')
  const hasUpdateAccess = (roleAccess: RoleAccess) => checkPermission(roleAccess, 'U')
  const hasDeleteAccess = (roleAccess: RoleAccess) => checkPermission(roleAccess, 'D')

  return {
    checkRole,
    checkPermission,
    getUserPermissions,
    hasCreateAccess,
    hasReadAccess,
    hasUpdateAccess,
    hasDeleteAccess,
  }
}
