const express = require('express'); const router = express.Router(); const DeviceHealthService = require('../services/deviceHealthService'); // Global instance (will be initialized on server start) let deviceHealthService = null; // Initialize the service reference const initializeHealthService = (service) => { deviceHealthService = service; }; // Get device health service status router.get('/status', (req, res) => { try { if (!deviceHealthService) { return res.status(503).json({ success: false, message: 'Device health service not initialized' }); } const status = deviceHealthService.getStatus(); res.json({ success: true, data: { ...status, checkIntervalMinutes: status.checkInterval / 60000, offlineThresholdMinutes: status.offlineThreshold / 60000 } }); } catch (error) { console.error('Error getting device health status:', error); res.status(500).json({ success: false, message: 'Failed to get device health status', error: process.env.NODE_ENV === 'development' ? error.message : 'Internal server error' }); } }); // Start device health monitoring router.post('/start', (req, res) => { try { if (!deviceHealthService) { return res.status(503).json({ success: false, message: 'Device health service not initialized' }); } deviceHealthService.start(); res.json({ success: true, message: 'Device health monitoring started' }); } catch (error) { console.error('Error starting device health service:', error); res.status(500).json({ success: false, message: 'Failed to start device health service', error: process.env.NODE_ENV === 'development' ? error.message : 'Internal server error' }); } }); // Stop device health monitoring router.post('/stop', (req, res) => { try { if (!deviceHealthService) { return res.status(503).json({ success: false, message: 'Device health service not initialized' }); } deviceHealthService.stop(); res.json({ success: true, message: 'Device health monitoring stopped' }); } catch (error) { console.error('Error stopping device health service:', error); res.status(500).json({ success: false, message: 'Failed to stop device health service', error: process.env.NODE_ENV === 'development' ? error.message : 'Internal server error' }); } }); // Trigger manual health check router.post('/check', async (req, res) => { try { if (!deviceHealthService) { return res.status(503).json({ success: false, message: 'Device health service not initialized' }); } await deviceHealthService.checkDeviceHealth(); res.json({ success: true, message: 'Manual health check completed' }); } catch (error) { console.error('Error running manual health check:', error); res.status(500).json({ success: false, message: 'Failed to run health check', error: process.env.NODE_ENV === 'development' ? error.message : 'Internal server error' }); } }); module.exports = { router, initializeHealthService };