const router = require('express').Router();
const { query: dbQuery } = require('../storage/postgres');
const { listInfluxSessions, querySessionHistory, exportSessionCSV } = require('../storage/influx');

/**
 * GET /sessions/history
 * Fonte primaria: InfluxDB (tag sensor + session sul measurement "logs").
 * Arricchisce con i metadati opzionali da PostgreSQL (sessiondataref): nome, tags, descrizione.
 */
router.get('/history', async (req, res) => {
    try {
        const sessions = await listInfluxSessions();

        let pgMap = {};
        try {
            const result = await dbQuery(
                `SELECT * FROM sessiondataref`,
                [],
                'sensors'
            );
            result.rows.forEach(r => { pgMap[r.session_id] = r; });
        } catch (_) {}

        const enriched = sessions.map(s => ({
            session_id: s.session,
            sensor_name: s.sensor,
            startTime: s.startTime,
            endTime: s.endTime,
            // campi opzionali da PostgreSQL
            name: pgMap[s.session]?.name || null,
            description: pgMap[s.session]?.description || null,
            tags: pgMap[s.session]?.tags || [],
        }));

        res.json(enriched);
    } catch (err) {
        console.error('[sessions] history error:', err.message);
        res.status(500).json({ error: 'internal server error' });
    }
});

/**
 * GET /sessions/:sensorId/data?session=sXXXX&from=ISO&to=ISO
 * Restituisce i dati storici di una sessione come JSON (righe pivotate da InfluxDB).
 */
router.get('/:sensorId/data', async (req, res) => {
    const { sensorId } = req.params;
    const { session, from, to } = req.query;

    if (!session) return res.status(400).json({ error: 'session param required' });

    try {
        let since = from || null;
        if (!since) {
            const result = await dbQuery(
                `SELECT created_at FROM sessiondataref WHERE session_id = $1`,
                [session],
                'sensors'
            );
            since = result.rows[0]?.created_at?.toISOString() || '-30d';
        }

        const until = to ? new Date(parseInt(to)).toISOString() : null;
        const rows = await querySessionHistory(sensorId, session, since, until);
        res.json(rows);
    } catch (err) {
        console.error('[sessions] data error:', err.message);
        res.status(500).json({ error: 'internal server error' });
    }
});

/**
 * GET /sessions/:sensorId/csv?session=sXXXX&from=ms&to=ms
 * Esporta i dati di una sessione come CSV (supporta intervallo opzionale).
 */
router.get('/:sensorId/csv', async (req, res) => {
    const { sensorId } = req.params;
    const { session, from, to } = req.query;

    if (!session) return res.status(400).json({ error: 'session param required' });

    try {
        let since = from ? new Date(parseInt(from)).toISOString() : null;
        if (!since) {
            const result = await dbQuery(
                `SELECT created_at FROM sessiondataref WHERE session_id = $1`,
                [session],
                'sensors'
            );
            since = result.rows[0]?.created_at?.toISOString() || '-30d';
        }

        const until = to ? new Date(parseInt(to)).toISOString() : null;
        const csv = await exportSessionCSV(sensorId, session, since, until);

        if (!csv) return res.status(404).json({ error: 'No data found for this session' });

        res.setHeader('Content-Type', 'text/csv');
        res.setHeader('Content-Disposition', `attachment; filename="session_${session}_${sensorId}.csv"`);
        res.send(csv);
    } catch (err) {
        console.error('[sessions] csv error:', err.message);
        res.status(500).json({ error: 'CSV export failed' });
    }
});

module.exports = router;
