import { ref } from 'vue'
import type { SidebarSection } from '~/shared/types'
import { onAuthSessionCleared } from '~/shared/stores/auth'

const sections = ref<SidebarSection[]>([])
const disabledRoutes = ref<string[]>([])
const loaded = ref(false)

function resetSidebarState(): void {
    sections.value = []
    disabledRoutes.value = []
    loaded.value = false
}

// Auto-enregistrement singleton : purge la sidebar sur 401/logout pour
// eviter qu'un nouvel utilisateur logue sur le meme onglet voie transitoirement
// les items de l'ancienne session (cf. CLAUDE.md : « composables avec state
// singleton doivent etre reinitialises au logout »).
onAuthSessionCleared(resetSidebarState)

export function useSidebar() {
    async function loadSidebar() {
        try {
            const api = useApi()
            const data = await api.get<{ sections: SidebarSection[]; disabledRoutes: string[] }>(
                '/sidebar',
                {},
                { toast: false }
            )
            sections.value = data.sections ?? []
            disabledRoutes.value = data.disabledRoutes ?? []
            loaded.value = true
        } catch {
            sections.value = []
            disabledRoutes.value = []
            loaded.value = true
        }
    }

    function isRouteDisabled(path: string): boolean {
        return disabledRoutes.value.some(
            disabled => path === disabled || path.startsWith(disabled + '/')
        )
    }

    function resetSidebar() {
        resetSidebarState()
    }

    return {
        sections,
        disabledRoutes,
        loaded,
        loadSidebar,
        resetSidebar,
        isRouteDisabled,
    }
}
