import { useAuthStore } from '../auth/auth-store'; const API_BASE = '/api'; async function apiFetch(path: string, options: RequestInit = {}): Promise { const token = useAuthStore.getState().accessToken; const headers: Record = { ...(options.headers as Record || {}), }; if (token) { headers['Authorization'] = `Bearer ${token}`; } if (!headers['Content-Type'] && !(options.body instanceof FormData)) { headers['Content-Type'] = 'application/json'; } const response = await fetch(`${API_BASE}${path}`, { ...options, headers }); if (response.status === 401) { useAuthStore.getState().logout(); window.location.href = '/login'; throw new Error('Unauthorized'); } if (!response.ok) { const text = await response.text(); throw new Error(`API error ${response.status}: ${text}`); } if (response.status === 204) return undefined as T; return response.json(); } export const api = { get: (path: string) => apiFetch(path), post: (path: string, body?: unknown) => apiFetch(path, { method: 'POST', body: body instanceof FormData ? body : JSON.stringify(body), }), patch: (path: string, body: unknown) => apiFetch(path, { method: 'PATCH', body: JSON.stringify(body) }), put: (path: string, body: FormData) => apiFetch(path, { method: 'PUT', body }), delete: (path: string) => apiFetch(path, { method: 'DELETE' }), };