import { useAuthStore } from '../store/authStore' const API_BASE = '' async function _silentRefresh(): Promise { const res = await fetch(`${API_BASE}/api/auth/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, credentials: 'include', }) if (!res.ok) return false const data = await res.json() const { user } = useAuthStore.getState() if (user) useAuthStore.getState().setAuth(data.access_token, user) return true } export async function apiFetch(path: string, options: RequestInit = {}): Promise { const token = useAuthStore.getState().accessToken const res = await fetch(`${API_BASE}${path}`, { ...options, headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}), ...options.headers, }, credentials: 'include', }) if (res.status === 401) { const refreshed = await _silentRefresh() if (!refreshed) { useAuthStore.getState().clearAuth() window.location.href = '/login' return res } const newToken = useAuthStore.getState().accessToken return fetch(`${API_BASE}${path}`, { ...options, headers: { 'Content-Type': 'application/json', ...(newToken ? { Authorization: `Bearer ${newToken}` } : {}), ...options.headers, }, credentials: 'include', }) } return res }