import axios, { type AxiosError } from 'axios' export const api = axios.create({ baseURL: process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:5000', headers: { 'Content-Type': 'application/json' }, }) // Inject auth token on every request api.interceptors.request.use((config) => { // TODO: replace with real token from cookie once auth is implemented const token = typeof window !== 'undefined' ? document.cookie.split('; ').find(r => r.startsWith('access-token='))?.split('=')[1] : null if (token) config.headers.Authorization = `Bearer ${token}` return config }) // Normalize error responses api.interceptors.response.use( (res) => res, (error: AxiosError<{ error: string }>) => { const status = error.response?.status if (status === 401) { // Redirect to login when auth is implemented if (typeof window !== 'undefined') window.location.href = '/login' } return Promise.reject(error) } ) // Helper to extract error message from API response export function getApiError(error: unknown): string { if (axios.isAxiosError(error)) { return error.response?.data?.error ?? error.message } return 'An unexpected error occurred' }