import { useAuthStore } from '@/stores/authStore'; const API_BASE = '/api'; async function request(path: string, options?: RequestInit): Promise { const response = await fetch(`${API_BASE}${path}`, { headers: { 'Content-Type': 'application/json', ...options?.headers, }, credentials: 'include', ...options, }); // On 401, try refreshing JWT first if (response.status === 401 && !path.includes('/auth/')) { const refreshRes = await fetch(`${API_BASE}/auth/refresh`, { method: 'POST', credentials: 'include' }); if (refreshRes.ok) { const retry = await fetch(`${API_BASE}${path}`, { headers: { 'Content-Type': 'application/json', ...options?.headers }, credentials: 'include', ...options, }); if (retry.ok) return retry.json(); } // JWT refresh failed — redirect to login useAuthStore.getState().logout(); window.location.href = '/login'; throw new Error('Non authentifié'); } if (!response.ok) { const error = await response.json().catch(() => ({ message: 'An error occurred' })); throw new Error(error.message || `HTTP ${response.status}`); } return response.json(); } export const api = { get: (path: string) => request(path), post: (path: string, body?: unknown) => request(path, { method: 'POST', body: body ? JSON.stringify(body) : undefined }), put: (path: string, body?: unknown) => request(path, { method: 'PUT', body: body ? JSON.stringify(body) : undefined }), patch: (path: string, body?: unknown) => request(path, { method: 'PATCH', body: body ? JSON.stringify(body) : undefined }), delete: (path: string) => request(path, { method: 'DELETE' }), };