export default defineNuxtRouteMiddleware(async (to) => {
    const auth = useAuthStore()
    const isLogin = to.path === '/login'

    if (!auth.checked) {
        await auth.ensureSession()
    }

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

    if (isLogin && auth.isAuthenticated) {
        return navigateTo('/')
    }

    const { loaded: sidebarLoaded, loadSidebar, resetSidebar } = useSidebar()
    const { loaded: modulesLoaded, loadModules, resetModules } = useModules()

    if (auth.isAuthenticated) {
        await Promise.all([
            sidebarLoaded.value ? Promise.resolve() : loadSidebar(),
            modulesLoaded.value ? Promise.resolve() : loadModules(),
        ])
    } else {
        // Logout / session expirée : purge l'état partagé pour le prochain login.
        resetSidebar()
        resetModules()
    }
})
