import { useState, useRequestHeaders, useRuntimeConfig } from '#imports' export interface Profile { id: string firstName: string lastName: string [key: string]: unknown } const buildUrl = (path: string): string => { const config = useRuntimeConfig() const base = (config.public.apiBaseUrl as string)?.replace(/\/$/, '') || '' return `${base}${path}` } export function useProfiles() { const profiles = useState('profiles:list', () => []) const loadingProfiles = useState('profiles:loading', () => false) const profilesLoaded = useState('profiles:loaded', () => false) const getSessionHeaders = (): Record | undefined => { if (!import.meta.server) { return undefined } const headers = useRequestHeaders(['cookie']) return headers?.cookie ? { cookie: headers.cookie } : undefined } const fetchProfiles = async (): Promise => { loadingProfiles.value = true try { profiles.value = await $fetch(buildUrl('/session/profiles'), { method: 'GET', credentials: 'include', headers: getSessionHeaders(), }) profilesLoaded.value = true } catch (error) { console.error('Erreur lors du chargement des profils', error) profiles.value = [] profilesLoaded.value = false } finally { loadingProfiles.value = false } return profiles.value } const createProfile = async ({ firstName, lastName }: { firstName: string; lastName: string }): Promise => { const profile = await $fetch(buildUrl('/session/profiles'), { method: 'POST', credentials: 'include', body: { firstName, lastName }, headers: getSessionHeaders(), }) await fetchProfiles() return profile } const deleteProfile = async (profileId: string): Promise => { await $fetch(buildUrl(`/session/profiles/${profileId}`), { method: 'DELETE', credentials: 'include', headers: getSessionHeaders(), }) await fetchProfiles() } return { profiles, loadingProfiles, profilesLoaded, fetchProfiles, createProfile, deleteProfile, } }