const router = require('express').Router();
const crypto = require('crypto');
const { query } = require('../storage/postgres');

const sets = ['forecasts', 'sensors', 'marine'];

function hashSensorCode(code) {
    return crypto.createHash('sha256').update(code).digest('hex');
}

/**
 * Middleware: valida sensor code e verifica che il sensore sia attivo.
 * Salva sensor.id in req.sensorId.
 */
async function authenticateSensor(req, res, next) {
    const { sensorCode } = req.params;
    try {
        const hashed = hashSensorCode(sensorCode);
        const sensor = await query(
            'SELECT id, active FROM sensors WHERE code_hash = $1',
            [hashed],
            'sensors'
        );

        if (!sensor.rows[0]) {
            return res.status(401).json({ error: 'Sensor code not valid' });
        }
        if (!sensor.rows[0].active) {
            return res.status(403).json({ error: 'Sensor is not active' });
        }

        req.sensorId = sensor.rows[0].id;
        next();
    } catch (err) {
        console.error('[PARAMS/SENSOR] Auth error:', err.message);
        res.status(500).json({ error: 'Internal server error' });
    }
}

/**
 * GET /params/sensor/:sensorCode/active?set=sensors
 * Ritorna il set di parametri attivo (forecasts, sensors, marine)
 */
router.get('/:sensorCode/active', authenticateSensor, async (req, res) => {
    const { set } = req.query;

    if (!set || !sets.includes(set))
        return res.status(400).json({ error: 'SET parameter invalid' });

    try {
        const result = await query(
            `SELECT * FROM ${set} WHERE active = true LIMIT 1`,
            [],
            'references'
        );

        res.json(result.rows[0] || null);
    } catch (err) {
        console.error('[PARAMS/SENSOR] Error:', err.message);
        res.status(500).json({ error: 'Internal server error' });
    }
});

module.exports = router;
