import { useAbility } from '@casl/vue'
import { useRedirect } from '~/composables/utils/useRedirect'

/**
 * Détermine les autorisations d'accès aux pages
 */
export default defineNuxtRouteMiddleware((to, _) => {
  const ability = useAbility()
  const candidates = to.matched.map((route) => route.name)

  const restrictedPages = ability.rules
    .filter((rule) => rule.action.toString() === 'display')
    .map((rule) => rule.subject.toString())

  candidates.forEach((routeName) => {
    const name: string = routeName?.toString() ?? ''

    // <<- TODO: remove after 2.5 release
    const runtimeConfig = useRuntimeConfig()
    if (
      runtimeConfig.public.env === 'production' &&
      (name === 'cmf_licence_page' || name === 'parameters_page')
    ) {
      const { redirectToHome } = useRedirect()
      redirectToHome()
    }
    // ->>

    if (
      name &&
      restrictedPages.includes(name) &&
      !ability.can('display', name)
    ) {
      console.error('No right to see this page')
      const { redirectToHome } = useRedirect()
      redirectToHome()
    }
  })
})
