const BASE = '/api' // ─── Token helpers ──────────────────────────────────────────────────────────── export function getToken() { return localStorage.getItem('token') } export function setToken(t) { t ? localStorage.setItem('token', t) : localStorage.removeItem('token') } function authHeaders(extra = {}) { const token = getToken() return token ? { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, ...extra } : { 'Content-Type': 'application/json', ...extra } } async function handleResponse(res) { if (res.status === 401) { setToken(null) window.dispatchEvent(new Event('auth:expired')) throw new Error('Session expirée, veuillez vous reconnecter.') } if (!res.ok) { const err = await res.json().catch(() => ({})) throw new Error(err.detail ?? `HTTP ${res.status}`) } return res.json() } // ─── Auth ───────────────────────────────────────────────────────────────────── export async function authStatus() { const res = await fetch(`${BASE}/auth/status`) return handleResponse(res) } export async function register(username, password) { const res = await fetch(`${BASE}/auth/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }), }) return handleResponse(res) } export async function login(username, password) { const res = await fetch(`${BASE}/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }), }) return handleResponse(res) } // ─── VPS ────────────────────────────────────────────────────────────────────── export async function fetchAllStatus() { const res = await fetch(`${BASE}/status`, { headers: authHeaders() }) return handleResponse(res) } export async function fetchLogs(vpsId, containerId, lines = 200) { const res = await fetch( `${BASE}/vps/${vpsId}/containers/${containerId}/logs?lines=${lines}`, { headers: authHeaders() } ) return handleResponse(res) } export async function containerAction(vpsId, containerId, action) { const res = await fetch(`${BASE}/vps/${vpsId}/containers/${containerId}/action`, { method: 'POST', headers: authHeaders(), body: JSON.stringify({ action }), }) return handleResponse(res) } export async function addVps(data) { const res = await fetch(`${BASE}/vps`, { method: 'POST', headers: authHeaders(), body: JSON.stringify(data), }) return handleResponse(res) } export async function deleteVps(vpsId) { const res = await fetch(`${BASE}/vps/${vpsId}`, { method: 'DELETE', headers: authHeaders(), }) return handleResponse(res) } export async function composeUpdate(vpsId, project) { const res = await fetch(`${BASE}/vps/${vpsId}/compose/update`, { method: 'POST', headers: authHeaders(), body: JSON.stringify({ project }), }) return handleResponse(res) } export async function updateVps(vpsId, data) { const res = await fetch(`${BASE}/vps/${vpsId}`, { method: 'PUT', headers: authHeaders(), body: JSON.stringify(data), }) return handleResponse(res) }