import axios, { type AxiosError } from 'axios' export const api = axios.create({ baseURL: process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:5089/api', headers: { 'Content-Type': 'application/json' }, withCredentials: true, }) type UnauthorizedHandler = () => void let unauthorizedHandler: UnauthorizedHandler | null = null export function registerUnauthorizedHandler(fn: UnauthorizedHandler): () => void { unauthorizedHandler = fn return () => { unauthorizedHandler = null } } api.interceptors.response.use( (res) => res, (error: AxiosError<{ error: string }>) => { const status = error.response?.status if (status === 401 && typeof window !== 'undefined' && window.location.pathname !== '/login') { unauthorizedHandler?.() return new Promise(() => {}) } return Promise.reject(error) } ) export function getApiError(error: unknown): string { if (axios.isAxiosError(error)) { return error.response?.data?.error ?? error.message } return 'An unexpected error occurred' }