import { getToken, clearSession } from './session'; import type { NetObject, ServiceInfo } from '../types'; const BACKEND = '/backend'; const AGENT = '/api'; export async function apiFetch(path: string, init: RequestInit = {}): Promise { const token = getToken(); const headers: Record = { 'Content-Type': 'application/json', ...(init.headers as Record ?? {}), }; if (token) headers['Authorization'] = `Bearer ${token}`; const res = await fetch(`${BACKEND}${path}`, { ...init, headers }); if (res.status === 401) { clearSession(); window.location.reload(); } return res; } export async function apiGet(path: string): Promise { const res = await apiFetch(path); if (!res.ok) throw new Error(`GET ${path} failed: ${res.status}`); return res.json(); } export async function apiPost(path: string, body?: unknown): Promise { const res = await apiFetch(path, { method: 'POST', body: body ? JSON.stringify(body) : undefined }); if (!res.ok) { const err = await res.json().catch(() => null); throw new Error(err?.detail ?? `POST ${path} failed: ${res.status}`); } return res.json(); } export async function apiPatch(path: string, body?: unknown): Promise { const res = await apiFetch(path, { method: 'PATCH', body: body ? JSON.stringify(body) : undefined }); if (!res.ok) { const err = await res.json().catch(() => null); throw new Error(err?.detail ?? `PATCH ${path} failed: ${res.status}`); } return res.json(); } export async function apiDelete(path: string): Promise { const res = await apiFetch(path, { method: 'DELETE' }); if (!res.ok) throw new Error(`DELETE ${path} failed: ${res.status}`); } // Inventory objects - authenticated via apiGet export async function fetchObjects(): Promise { return apiGet('/objects'); } // Legacy agent calls (unauthenticated local agent) export async function fetchServices(): Promise { const res = await fetch(`${AGENT}/services`); if (!res.ok) throw new Error('Impossibile leggere lo stato dei servizi'); return res.json(); } export async function serviceAction(name: string, action: 'start' | 'stop' | 'restart') { const res = await fetch(`${AGENT}/services/${encodeURIComponent(name)}/${action}`, { method: 'POST' }); if (!res.ok) throw new Error(`Azione ${action} fallita su ${name}`); return res.json(); }