const BASE_URL = import.meta.env.DEV ? 'http://localhost:8000' : ''; interface RequestOptions extends RequestInit { params?: Record; } async function request(path: string, options: RequestOptions = {}): Promise { const token = localStorage.getItem('vibra_token'); // Setup headers const headers = new Headers(options.headers); if (token && !headers.has('Authorization')) { headers.set('Authorization', `Bearer ${token}`); } if (!headers.has('Content-Type') && !(options.body instanceof FormData)) { headers.set('Content-Type', 'application/json'); } // Setup Query parameters let url = `${BASE_URL}${path}`; if (options.params) { const searchParams = new URLSearchParams(options.params); url += `?${searchParams.toString()}`; } const response = await fetch(url, { ...options, headers, }); if (!response.ok) { let errorMessage = `Request failed: ${response.statusText}`; try { const errorData = await response.json(); errorMessage = errorData.detail || errorMessage; } catch { // JSON parsing failed, use fallback message } throw new Error(errorMessage); } // Return empty response if 204 No Content if (response.status === 204) { return {} as T; } return response.json(); } export const api = { get: (path: string, options?: RequestOptions) => request(path, { ...options, method: 'GET' }), post: (path: string, body?: any, options?: RequestOptions) => request(path, { ...options, method: 'POST', body: body instanceof FormData ? body : JSON.stringify(body) }), put: (path: string, body?: any, options?: RequestOptions) => request(path, { ...options, method: 'PUT', body: JSON.stringify(body) }), delete: (path: string, options?: RequestOptions) => request(path, { ...options, method: 'DELETE' }), };