import { FastifyInstance } from "fastify"; import { eq } from "drizzle-orm"; import { db } from "../../../db"; // <--- PFAD ZUR DB INSTANZ ANPASSEN import { devices } from "../../../db/schema"; // Definition, was wir vom ESP32 erwarten interface HealthBody { terminal_id: string; ip_address?: string; wifi_rssi?: number; uptime_seconds?: number; heap_free?: number; [key: string]: any; // Erlaubt weitere Felder } export default async function devicesManagementRoutes(server: FastifyInstance) { server.post<{ Body: HealthBody }>( "/health", async (req, reply) => { try { const data = req.body; // 1. Validierung: Haben wir eine ID? if (!data.terminal_id) { console.warn("Health Check ohne terminal_id empfangen:", data); return reply.code(400).send({ error: "terminal_id missing" }); } console.log(`Health Ping von Device ${data.terminal_id}`, data); // 2. Datenbank Update // Wir suchen das Gerät mit der passenden externalId const result = await server.db .update(devices) .set({ lastSeen: new Date(), // Setzt Zeit auf JETZT lastDebugInfo: data // Speichert das ganze JSON }) .where(eq(devices.externalId, data.terminal_id)) .returning({ id: devices.id }); // Gibt ID zurück, falls gefunden // 3. Checken ob Gerät gefunden wurde if (result.length === 0) { console.warn(`Unbekanntes Terminal versucht Health Check: ${data.terminal_id}`); // Optional: 404 senden oder ignorieren (Sicherheit) return reply.code(404).send({ error: "Device not found" }); } // Alles OK return reply.code(200).send({ status: "ok" }); } catch (err: any) { console.error("Health Check Error:", err); return reply.code(500).send({ error: err.message }); } } ); }