import axios, { InternalAxiosRequestConfig } from 'axios'; import { getAdminAuthSnapshot } from '~/shared/libs/admin-auth'; const API_BASE_PATH = '/api/v1'; const isBrowser = typeof window !== 'undefined'; const readStorage = (key: string) => { if (!isBrowser) { return null; } try { return window.localStorage.getItem(key); } catch (error) { console.error('Failed to access localStorage', error); return null; } }; type RequestConfig = InternalAxiosRequestConfig; const resolveDefaultBaseUrl = () => { const envBase = (import.meta.env.VITE_API_BASE_URL ?? '').trim(); if (envBase) { return envBase.replace(/\/$/, ''); } if (isBrowser) { return `${window.location.origin.replace(/\/$/, '')}${API_BASE_PATH}`; } return API_BASE_PATH; }; const DEFAULT_API_BASE_URL = resolveDefaultBaseUrl(); export const request = axios.create({ withCredentials: true }); request.interceptors.request.use((config: RequestConfig) => { config.headers = config.headers ?? {}; const headers = config.headers as Record; const authToken = readStorage('auth_v1_token'); if (authToken && !headers.Authorization) { headers.Authorization = authToken; } const urlPath = config.url ?? ''; if (urlPath.startsWith('/admin')) { const { token, headerName } = getAdminAuthSnapshot(); if (token) { const headerKey = headerName || 'X-Admin-Token'; if (!headers[headerKey]) { headers[headerKey] = token; } } } if (!config.baseURL) { config.baseURL = DEFAULT_API_BASE_URL; } return config; }); request.interceptors.response.use((response) => response);