import { useState, useRequestHeaders, useRuntimeConfig } from '#imports' const buildUrl = (path) => { const config = useRuntimeConfig() const base = config.public.apiBaseUrl?.replace(/\/$/, '') || '' return `${base}${path}` } export function useProfileSession() { const activeProfile = useState('profileSession:active', () => null) const sessionLoaded = useState('profileSession:loaded', () => false) const loading = useState('profileSession:loading', () => false) const getSessionHeaders = () => { if (!process.server) return undefined const headers = useRequestHeaders(['cookie']) return headers?.cookie ? { cookie: headers.cookie } : undefined } const fetchCurrentProfile = async () => { loading.value = true try { activeProfile.value = await $fetch(buildUrl('/session/profile'), { method: 'GET', credentials: 'include', headers: getSessionHeaders(), }) } catch (error) { if (error?.status === 401) { activeProfile.value = null } else { console.error('Erreur lors du chargement du profil actif', error) activeProfile.value = null } } finally { sessionLoaded.value = true loading.value = false } return activeProfile.value } const ensureSession = () => { if (!sessionLoaded.value) { return fetchCurrentProfile() } return Promise.resolve(activeProfile.value) } const activateProfile = async (profileId) => { await $fetch(buildUrl('/session/profile'), { method: 'POST', credentials: 'include', body: { profileId }, headers: getSessionHeaders(), }) await fetchCurrentProfile() } const logout = async () => { try { await $fetch(buildUrl('/session/profile'), { method: 'DELETE', credentials: 'include', headers: getSessionHeaders(), }) } finally { activeProfile.value = null sessionLoaded.value = true } } return { activeProfile, loading, sessionLoaded, ensureSession, fetchCurrentProfile, activateProfile, logout, } }