const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const JWT_CONFIG = require('../config/jwt');
const { requireAdmin } = require('../middleware/roleCheck');
const ctrl = require('../controllers/networkMonitor.controller');

// Auth that also accepts token from query param (needed for SSE / EventSource)
function authTokenOrQuery(req, res, next) {
    const authHeader = req.headers['authorization'];
    const token = (authHeader && authHeader.split(' ')[1]) || req.query.token;
    if (!token) return res.status(401).json({ status: 'error', message: 'Token required' });
    try {
        req.user = jwt.verify(token, JWT_CONFIG.secret);
        next();
    } catch {
        res.status(403).json({ status: 'error', message: 'Invalid token' });
    }
}

router.post('/discover',    authTokenOrQuery, requireAdmin, ctrl.discover);
router.get('/sse',          authTokenOrQuery, requireAdmin, ctrl.sseStream);
router.get('/statistics',   authTokenOrQuery, requireAdmin, ctrl.getStatistics);
router.get('/uptime-stats', authTokenOrQuery, requireAdmin, ctrl.getAllUptimeStats);
router.get('/',             authTokenOrQuery, requireAdmin, ctrl.getAll);
router.post('/',            authTokenOrQuery, requireAdmin, ctrl.createDevice);
router.get('/:id/checks',   authTokenOrQuery, requireAdmin, ctrl.getChecks);
router.post('/:id/check-now', authTokenOrQuery, requireAdmin, ctrl.checkNow);
router.put('/:id',          authTokenOrQuery, requireAdmin, ctrl.updateDevice);
router.delete('/:id',       authTokenOrQuery, requireAdmin, ctrl.deleteDevice);

module.exports = router;
