import { supabase } from '../lib/supabase' const API_BASE = import.meta.env['VITE_API_URL'] ?? '' export class ApiError extends Error { status: number constructor(status: number, message: string) { super(message) this.name = 'ApiError' this.status = status } } async function getAuthHeaders(): Promise> { const { data } = await supabase.auth.getSession() if (data.session?.access_token) { return { Authorization: `Bearer ${data.session.access_token}` } } return {} } async function request(path: string, options?: RequestInit): Promise { const authHeaders = await getAuthHeaders() const res = await fetch(`${API_BASE}/api/v1${path}`, { ...options, headers: { 'Content-Type': 'application/json', ...authHeaders, ...options?.headers, }, }) if (!res.ok) { const body = await res.json().catch(() => ({})) throw new ApiError(res.status, body.detail ?? res.statusText) } if (res.status === 204) return undefined as T return res.json() } export const api = { get: (path: string) => request(path), post: (path: string, body: unknown) => request(path, { method: 'POST', body: JSON.stringify(body), }), patch: (path: string, body: unknown) => request(path, { method: 'PATCH', body: JSON.stringify(body), }), put: (path: string, body: unknown) => request(path, { method: 'PUT', body: JSON.stringify(body), }), del: (path: string) => request(path, { method: 'DELETE' }), }