import { getStoredToken } from './auth-context'; import { getTenantFromPath } from './tenant-context'; const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'; function getHeaders(): HeadersInit { const token = getStoredToken(); return { 'Content-Type': 'application/json', ...(token ? { 'Authorization': `Bearer ${token}` } : {}), }; } async function parseErrorDetail(res: Response): Promise { try { const body = await res.json(); return body.detail || body.message || 'API request failed'; } catch { return 'API request failed'; } } export async function fetcher(url: string): Promise { const res = await fetch(`${API_BASE_URL}${url}`, { headers: getHeaders(), }); if (!res.ok) { const detail = await parseErrorDetail(res); throw new Error(detail); } return res.json(); } export function getTenantUrl(path: string, tenantId?: string): string { const tenant = tenantId || getTenantFromPath(); if (!tenant) { throw new Error('Tenant ID not found'); } return `/api/${tenant}${path}`; } export const api = { get: (url: string) => fetcher(url), post: async (url: string, data: unknown): Promise => { const res = await fetch(`${API_BASE_URL}${url}`, { method: 'POST', headers: getHeaders(), body: JSON.stringify(data), }); if (!res.ok) throw new Error(await parseErrorDetail(res)); return res.json(); }, put: async (url: string, data: unknown): Promise => { const res = await fetch(`${API_BASE_URL}${url}`, { method: 'PUT', headers: getHeaders(), body: JSON.stringify(data), }); if (!res.ok) throw new Error(await parseErrorDetail(res)); return res.json(); }, patch: async (url: string, data: unknown): Promise => { const res = await fetch(`${API_BASE_URL}${url}`, { method: 'PATCH', headers: getHeaders(), body: JSON.stringify(data), }); if (!res.ok) throw new Error(await parseErrorDetail(res)); return res.json(); }, delete: async (url: string): Promise => { const res = await fetch(`${API_BASE_URL}${url}`, { method: 'DELETE', headers: getHeaders(), }); if (!res.ok) throw new Error(await parseErrorDetail(res)); return res.json(); }, };