import { getAccessToken, login } from '../auth' const BASE = '/api' async function request(path: string, options: RequestInit = {}): Promise { const token = getAccessToken() if (!token) { login(window.location.pathname); throw new Error('Not authenticated') } const res = await fetch(`${BASE}${path}`, { ...options, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, ...options.headers }, }) if (res.status === 401) { login(window.location.pathname); throw new Error('Unauthorized') } if (!res.ok) throw new Error(`HTTP ${res.status}`) return res.json() as Promise } export function useApi() { return { get: (path: string) => request(path), post: (path: string, body?: unknown) => request(path, { method: 'POST', ...(body !== undefined ? { body: JSON.stringify(body) } : {}) }), put: (path: string, body?: unknown) => request(path, { method: 'PUT', ...(body !== undefined ? { body: JSON.stringify(body) } : {}) }), del: (path: string) => request(path, { method: 'DELETE' }), } }