import { authClient } from './auth-client'; /** * Central API client for all network requests * Automatically attaches auth cookies to every request */ export async function apiFetch(endpoint: string, options: RequestInit = {}): Promise { const baseURL = process.env.EXPO_PUBLIC_API_URL || 'http://localhost:3001'; const url = `${baseURL}${endpoint}`; // Get auth cookies const cookies = authClient.getCookie(); const headers: Record = { 'Content-Type': 'application/json', ...(typeof options.headers === 'object' ? (options.headers as Record) : {}), }; if (cookies) { headers.Cookie = cookies; } const response = await fetch(url, { ...options, headers, credentials: 'omit', // Prevent conflicts with manually set Cookie header }); if (!response.ok) { const error = await response.json().catch(() => ({ message: 'Unknown error' })); throw new Error(error.message || `API error: ${response.status}`); } return response.json(); } // Convenience methods export const api = { get: (endpoint: string) => apiFetch(endpoint, { method: 'GET' }), post: (endpoint: string, body?: unknown) => apiFetch(endpoint, { method: 'POST', body: body ? JSON.stringify(body) : undefined, }), put: (endpoint: string, body?: unknown) => apiFetch(endpoint, { method: 'PUT', body: body ? JSON.stringify(body) : undefined, }), delete: (endpoint: string) => apiFetch(endpoint, { method: 'DELETE' }), };