import type { Permission, RoleAccesses } from '~/models/role'
import { systemCode } from '~/const/common/role'

export interface PageOperationPermission {
  canRead: boolean
  canCreate: boolean
  canUpdate: boolean
  canDelete: boolean
}

/**
 * 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 = (roleAccesses: RoleAccesses, _userRoles?: string[]): boolean => {
    const activeRole = authStore.getActiveRole() || ''
    if (activeRole === systemCode) {
      return true
    }
    return (activeRole in roleAccesses);
  }

  const checkPermission = (roleAccesses: RoleAccesses, permission: Permission, _userRoles?: string[]): boolean => {
    const activeRole = authStore.getActiveRole() || ''
    if (activeRole === systemCode) {
      return true
    }
    if (activeRole in roleAccesses && roleAccesses[activeRole]) {
      return roleAccesses[activeRole].includes(permission)
    }
    return false
  }

  const getUserPermissions = (roleAccess: RoleAccesses, _userRoles?: string[]): Permission[] => {
    const roles = authStore.userRoles
    const permissions = new Set<Permission>()

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

    return Array.from(permissions)
  }

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

  const getPagePermissions = (roleAccess: RoleAccesses): PageOperationPermission => ({
      canRead : hasReadAccess(roleAccess),
      canCreate: hasCreateAccess(roleAccess),
      canUpdate: hasUpdateAccess(roleAccess),
      canDelete: hasDeleteAccess(roleAccess),
  })

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

  }
}
