import { useState, useRequestHeaders, useRuntimeConfig } from '#imports' import type { Profile } from './useProfiles' const buildUrl = (path: string): string => { const config = useRuntimeConfig() const baseUrl = import.meta.server ? ((config.apiBaseUrl as string) || (config.public.apiBaseUrl as string) || '') : ((config.public.apiBaseUrl as string) || '') const base = baseUrl.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 = (): Record | undefined => { if (!import.meta.server) { return undefined } const headers = useRequestHeaders(['cookie']) return headers?.cookie ? { cookie: headers.cookie } : undefined } const fetchCurrentProfile = async (): Promise => { loading.value = true try { activeProfile.value = await $fetch(buildUrl('/session/profile'), { method: 'GET', credentials: 'include', headers: getSessionHeaders(), }) } catch (error) { const err = error as { status?: number } if (err?.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 = (): Promise => { if (!sessionLoaded.value) { return fetchCurrentProfile() } return Promise.resolve(activeProfile.value) } const activateProfile = async (profileId: string): Promise => { await $fetch(buildUrl('/session/profile'), { method: 'POST', credentials: 'include', body: { profileId }, headers: getSessionHeaders(), }) await fetchCurrentProfile() } const logout = async (): Promise => { 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, } }