import type { ChartConfig, AlertConfig, TriggeredAlert, SignalRow, SessionBoundary, UpsRow, TimeMode, } from './types'; let _token = ''; export function setToken(token: string) { _token = token; } function url( path: string, params: Record = {}, ) { const u = new URL( path, typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3000', ); u.searchParams.set('token', _token); for (const [k, v] of Object.entries(params)) { if (v === undefined) continue; if (Array.isArray(v)) v.forEach((val) => u.searchParams.append(k, String(val))); else u.searchParams.set(k, String(v)); } return u.toString(); } async function get( path: string, params?: Record, ): Promise { const res = await fetch(url(path, params)); if (!res.ok) throw new Error(`${res.status} ${res.statusText}`); return res.json(); } async function mutate(method: string, path: string, body?: unknown): Promise { const res = await fetch(url(path), { method, headers: { 'Content-Type': 'application/json' }, body: body !== undefined ? JSON.stringify(body) : undefined, }); if (!res.ok) throw new Error(`${res.status} ${res.statusText}`); return res.json(); } export function fetchSignals(params: { combinator?: string[]; item?: string[]; exclude?: string[]; signal?: string; time_mode?: TimeMode; from?: string; to?: string; regex?: boolean; order_by?: string; limit?: number; }): Promise { return get('/api/signals', params as Record); } export function fetchUps(params: { combinator?: string; from?: string; to?: string; }): Promise { return get('/api/ups', params); } export function fetchSessions(from: string, to: string): Promise { return get('/api/sessions', { from, to }); } export function fetchCharts(): Promise { return get('/api/charts'); } export function createChart(body: Omit): Promise { return mutate('POST', '/api/charts', body); } export function updateChart(id: string, body: Partial): Promise { return mutate('PUT', `/api/charts/${id}`, body); } export function deleteChart(id: string): Promise<{ ok: boolean }> { return mutate('DELETE', `/api/charts/${id}`); } export function fetchAlerts(): Promise { return get('/api/alerts'); } export function createAlert(body: Omit): Promise { return mutate('POST', '/api/alerts', body); } export function updateAlert(id: string, body: Partial): Promise { return mutate('PUT', `/api/alerts/${id}`, body); } export function deleteAlert(id: string): Promise<{ ok: boolean }> { return mutate('DELETE', `/api/alerts/${id}`); } export function checkAlerts(): Promise { return get('/api/alerts/check'); }