import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; import type Database from "better-sqlite3"; import { getLatestSnapshots, getRecentHistory } from "../db/index.js"; async function requireAuth(req: FastifyRequest, reply: FastifyReply) { if (!req.session.username) { reply.code(401).send({ error: "not authenticated" }); } } export function registerHostRoutes(app: FastifyInstance, db: Database.Database): void { app.get("/api/hosts", { preHandler: requireAuth }, async () => { const rows = getLatestSnapshots(db); const history = new Map(); for (const h of getRecentHistory(db)) { if (!history.has(h.host_id)) history.set(h.host_id, []); history.get(h.host_id)!.push({ ts: h.ts, cpuPct: h.cpu_pct, memPct: h.mem_pct, diskPct: h.disk_pct }); } return { hosts: rows.map((r) => ({ hostId: r.host_id, displayName: r.display_name, group: r.group_name, status: r.status, cpuPct: r.cpu_pct, memPct: r.mem_pct, diskPct: r.disk_pct, memTotalBytes: r.mem_total_bytes, memUsedBytes: r.mem_used_bytes, diskTotalBytes: r.disk_total_bytes, diskUsedBytes: r.disk_used_bytes, memPressurePct: r.mem_pressure_pct, cpuPressurePct: r.cpu_pressure_pct, uptimeSec: r.uptime_sec, lastSeen: r.ts, history: history.get(r.host_id) ?? [], })), }; }); app.get("/api/health", async () => ({ ok: true })); }