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

export function usePageChecker() {
  const route = useRoute()
  const { checkRole, hasCreateAccess, hasReadAccess, hasUpdateAccess, hasDeleteAccess } = useRBAC()

  function getRouteTitle() {
    return route.meta.title as string
  }

  function getParamsId() {
    const id = route.params.id
    return typeof id === 'string' ? parseInt(id) : 0
  }

  function getPageAccess(
    roleAccess: Record<string, Permission[]>,
    type: 'create' | 'read' | 'update' | 'delete',
  ) {
    // Check if user has access to this page, need to use try - catch for proper handling
    const hasAccess = checkRole(roleAccess)
    if (!hasAccess) {
      navigateTo('/403')
    }

    // Define permission-based computed properties
    const canCreate = hasCreateAccess(roleAccess)
    const canRead = hasReadAccess(roleAccess)
    const canUpdate = hasUpdateAccess(roleAccess)
    const canDelete = hasDeleteAccess(roleAccess)

    switch (type) {
      case 'create':
        return canCreate
      case 'read':
        return canRead
      case 'update':
        return canUpdate
      case 'delete':
        return canDelete
      default:
        return false
    }
  }

  return {
    checkRole,
    hasCreateAccess,
    hasReadAccess,
    hasUpdateAccess,
    hasDeleteAccess,
    getRouteTitle,
    getParamsId,
    getPageAccess
  }
}
