local db = require("db") local log = require("log") local DeviceHandler = {} function DeviceHandler.handle(event) local conn, err = db.get_connection() if not conn then error("Database connection failed: " .. tostring(err)) end local ok, handler_err = pcall(function() conn:query([[ CREATE TABLE IF NOT EXISTS device_events ( id SERIAL PRIMARY KEY, device_id INTEGER, device_name VARCHAR(255), event_type VARCHAR(100), processed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ]]) conn:query( "INSERT INTO device_events (device_id, device_name, event_type) VALUES ($1, $2, $3)", tonumber(event.device_id) or 0, event.device_name or "", event.event_type ) end) conn:disconnect() if not ok then error(handler_err) end log.info("Device event logged", { component = "device_handler", device_name = event.device_name, request_id = event.request_id, }) end return DeviceHandler