import type { Service, Heartbeat } from '$lib/types'; export interface EnhancedService extends Service { heartbeats: Heartbeat[]; } export interface InitialLogEntry { kind: 'check' | 'created' | 'deleted' | 'transition'; serviceName: string; serviceUrl: string; timestamp: Date; hb?: Heartbeat; wasUp?: boolean; } export async function load({ fetch }) { let services: EnhancedService[] = []; let error = ''; let initialLog: InitialLogEntry[] = []; try { const res = await fetch('/api/services'); if (!res.ok) throw new Error(`HTTP ${res.status}`); const list: Service[] = await res.json(); services = await Promise.all( list.map(async (svc) => { try { const hres = await fetch(`/api/services/${svc.id}/history`); if (!hres.ok) throw new Error(`HTTP ${hres.status}`); const json = await hres.json(); const heartbeats: Heartbeat[] = Array.isArray(json) ? json : (json.data ?? []); return { ...svc, heartbeats }; } catch { return { ...svc, heartbeats: [] }; } }) ); initialLog = []; for (const svc of services) { const hbs = svc.heartbeats; if (hbs.length === 0) continue; const last = hbs[hbs.length - 1]; initialLog.push({ kind: 'check', serviceName: svc.name, serviceUrl: svc.url, timestamp: new Date(last.tested_at), hb: last }); if (hbs.length >= 2) { const prev = hbs[hbs.length - 2]; if (prev.is_up !== last.is_up) { initialLog.push({ kind: 'transition', serviceName: svc.name, serviceUrl: svc.url, timestamp: new Date(last.tested_at), hb: last, wasUp: prev.is_up }); } } } initialLog.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime()); initialLog = initialLog.slice(0, 50); } catch (e) { error = 'Não foi possível conectar ao servidor'; } return { services, error, initialLog }; }