/** * API Service Client with Token Interceptor, Tenant Context Header, and Error Boundaries. * * Fulfills FR-AUTH-001, FR-AUTH-002, FR-AUTH-003, and FR-TENANTMEMBERSHIPCONTEXT-002. */ import { authStore } from '../stores/authStore'; import { tenantStore } from '../stores/tenantStore'; const BASE_URL = (typeof process !== 'undefined' && process.env?.VITE_API_URL) ? process.env.VITE_API_URL : (typeof window !== 'undefined' ? '' : 'http://localhost:8000'); export interface ApiResponse { data?: T; error?: string; status: number; } export interface ApiClientFn { (endpoint: string, options?: RequestInit): Promise>; get(endpoint: string, options?: RequestInit): Promise; post(endpoint: string, body?: any, options?: RequestInit): Promise; patch(endpoint: string, body?: any, options?: RequestInit): Promise; delete(endpoint: string, options?: RequestInit): Promise; } const baseApiClient = async function( endpoint: string, options: RequestInit = {} ): Promise> { const token = authStore.getState().accessToken; const activeTenantId = tenantStore.getState().activeTenantId; const headers = new Headers(options.headers || {}); headers.set('Accept', 'application/json'); if (token) { headers.set('Authorization', `Bearer ${token}`); } if (activeTenantId && !headers.has('X-Tenant-ID')) { headers.set('X-Tenant-ID', activeTenantId); } try { const response = await fetch(`${BASE_URL}${endpoint}`, { ...options, headers, }); // Catch 401 Unauthorized -> trigger client logout if (response.status === 401) { authStore.logout(); tenantStore.clearTenant(); if (typeof window !== 'undefined' && !window.location.pathname.startsWith('/login')) { window.location.href = '/login?error=SESSION_EXPIRED'; } return { status: 401, error: 'SESSION_EXPIRED' }; } // Catch 403 Forbidden -> redirect or flag access denied if (response.status === 403) { const errBody = await response.json().catch(() => null); if (errBody?.code === 'TENANT_NOT_ACTIVE') { if (typeof window !== 'undefined') { window.location.href = '/access-denied?reason=TENANT_SUSPENDED'; } } return { status: 403, error: errBody?.error || 'ACCESS_DENIED', data: errBody }; } const data = await response.json().catch(() => null); return { data, status: response.status }; } catch (err: any) { return { status: 500, error: err.message || 'NETWORK_ERROR' }; } }; export const apiClient = baseApiClient as ApiClientFn; apiClient.get = async function(endpoint: string, options: RequestInit = {}): Promise { const res = await baseApiClient(endpoint, { ...options, method: 'GET' }); if (res.status >= 400) { const error: any = new Error(res.error || `HTTP ${res.status}`); error.response = res; throw error; } return res.data as T; }; apiClient.post = async function(endpoint: string, body?: any, options: RequestInit = {}): Promise { const res = await baseApiClient(endpoint, { ...options, method: 'POST', headers: { 'Content-Type': 'application/json', ...(options.headers || {}) }, body: body !== undefined ? JSON.stringify(body) : undefined, }); if (res.status >= 400) { const error: any = new Error(res.error || `HTTP ${res.status}`); error.response = res; throw error; } return res.data as T; }; apiClient.patch = async function(endpoint: string, body?: any, options: RequestInit = {}): Promise { const res = await baseApiClient(endpoint, { ...options, method: 'PATCH', headers: { 'Content-Type': 'application/json', ...(options.headers || {}) }, body: body !== undefined ? JSON.stringify(body) : undefined, }); if (res.status >= 400) { const error: any = new Error(res.error || `HTTP ${res.status}`); error.response = res; throw error; } return res.data as T; }; apiClient.delete = async function(endpoint: string, options: RequestInit = {}): Promise { const res = await baseApiClient(endpoint, { ...options, method: 'DELETE' }); if (res.status >= 400) { const error: any = new Error(res.error || `HTTP ${res.status}`); error.response = res; throw error; } return res.data as T; };