export default defineNuxtRouteMiddleware((to) => {
    const auth = useAuthStore()

    if (!auth.isAuthenticated) {
        return navigateTo('/login')
    }

    // Gate the route on the RBAC permission(s) declared via definePageMeta.
    // A string requires that single permission; an array requires ANY of them.
    // ROLE_ADMIN bypasses everything through usePermissions().can().
    const required = to.meta.permission

    if (required === undefined) {
        return
    }

    const { canAny } = usePermissions()
    const codes = Array.isArray(required) ? required : [required]

    if (!canAny(codes)) {
        return navigateTo('/')
    }
})
