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

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

/* ─── READS ─── */

/**
 * GET /params/active?set=sensors
 * Restituisce il set attivo per il tipo richiesto
 */
router.get('/active', 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] Error reading active set:', err.message);
        res.status(500).json({ error: 'Internal server error' });
    }
});

/**
 * GET /params/sets?type=sensors
 * Lista tutti i set di un tipo (con paginazione)
 */
router.get('/sets', async (req, res) => {
    const { type } = req.query;
    if (!type || !sets.includes(type))
        return res.status(400).json({ error: 'type parameter invalid' });

    try {
        const result = await query(
            `SELECT id, name, description, mayor, minor, patch, state, active, tags, created_at, updated_at
             FROM ${type} ORDER BY updated_at DESC`,
            [], 'references'
        );
        res.json(result.rows);
    } catch (err) {
        console.error('[PARAMS] Error listing sets:', err.message);
        res.status(500).json({ error: 'Internal server error' });
    }
});

/**
 * GET /params/sets/:id?type=sensors
 * Restituisce un singolo set completo (con content)
 */
router.get('/sets/:id', async (req, res) => {
    const { type } = req.query;
    const { id } = req.params;
    if (!type || !sets.includes(type))
        return res.status(400).json({ error: 'type parameter invalid' });

    try {
        const result = await query(`SELECT * FROM ${type} WHERE id = $1`, [id], 'references');
        if (!result.rows[0]) return res.status(404).json({ error: 'Set not found' });
        res.json(result.rows[0]);
    } catch (err) {
        console.error('[PARAMS] Error reading set:', err.message);
        res.status(500).json({ error: 'Internal server error' });
    }
});


/* ─── WRITES ─── */

/**
 * POST /params/sets?type=sensors
 * Crea un nuovo set di regole
 */
router.post('/sets', async (req, res) => {
    const { type } = req.query;
    if (!type || !sets.includes(type))
        return res.status(400).json({ error: 'type parameter invalid' });

    const { name, description, content, tags } = req.body;
    if (!name || !content) return res.status(400).json({ error: 'name and content required' });

    try {
        const result = await query(
            `INSERT INTO ${type} (name, description, mayor, minor, patch, state, active, tags, content)
             VALUES ($1, $2, 1, 0, 0, 'draft', false, $3, $4) RETURNING *`,
            [name, description || '', tags || [], JSON.stringify(content)],
            'references'
        );
        res.status(201).json(result.rows[0]);
    } catch (err) {
        console.error('[PARAMS] Error creating set:', err.message);
        res.status(500).json({ error: 'Internal server error' });
    }
});

/**
 * PUT /params/sets/:id?type=sensors
 * Aggiorna un set esistente
 */
router.put('/sets/:id', async (req, res) => {
    const { type } = req.query;
    const { id } = req.params;
    if (!type || !sets.includes(type))
        return res.status(400).json({ error: 'type parameter invalid' });

    const { name, description, content, tags, state } = req.body;

    try {
        const fields = [];
        const values = [];
        let idx = 1;

        if (name !== undefined) { fields.push(`name = $${idx++}`); values.push(name); }
        if (description !== undefined) { fields.push(`description = $${idx++}`); values.push(description); }
        if (content !== undefined) { fields.push(`content = $${idx++}`); values.push(JSON.stringify(content)); }
        if (tags !== undefined) { fields.push(`tags = $${idx++}`); values.push(tags); }
        if (state !== undefined) { fields.push(`state = $${idx++}`); values.push(state); }

        if (fields.length === 0) return res.status(400).json({ error: 'No fields to update' });

        fields.push(`updated_at = NOW()`);
        values.push(id);

        const result = await query(
            `UPDATE ${type} SET ${fields.join(', ')} WHERE id = $${idx} RETURNING *`,
            values, 'references'
        );

        if (!result.rows[0]) return res.status(404).json({ error: 'Set not found' });
        res.json(result.rows[0]);
    } catch (err) {
        console.error('[PARAMS] Error updating set:', err.message);
        res.status(500).json({ error: 'Internal server error' });
    }
});

/**
 * POST /params/sets/:id/activate?type=sensors
 * Attiva un set (disattiva tutti gli altri dello stesso tipo)
 */
router.post('/sets/:id/activate', async (req, res) => {
    const { type } = req.query;
    const { id } = req.params;
    if (!type || !sets.includes(type))
        return res.status(400).json({ error: 'type parameter invalid' });

    try {
        // Disattiva tutti
        await query(`UPDATE ${type} SET active = false WHERE active = true`, [], 'references');
        // Attiva quello richiesto
        const result = await query(
            `UPDATE ${type} SET active = true, state = 'active', updated_at = NOW() WHERE id = $1 RETURNING *`,
            [id], 'references'
        );

        if (!result.rows[0]) return res.status(404).json({ error: 'Set not found' });
        res.json(result.rows[0]);
    } catch (err) {
        console.error('[PARAMS] Error activating set:', err.message);
        res.status(500).json({ error: 'Internal server error' });
    }
});

/**
 * DELETE /params/sets/:id?type=sensors
 * Elimina un set (solo se non attivo)
 */
router.delete('/sets/:id', async (req, res) => {
    const { type } = req.query;
    const { id } = req.params;
    if (!type || !sets.includes(type))
        return res.status(400).json({ error: 'type parameter invalid' });

    try {
        // Controlla che non sia attivo
        const check = await query(`SELECT active FROM ${type} WHERE id = $1`, [id], 'references');
        if (!check.rows[0]) return res.status(404).json({ error: 'Set not found' });
        if (check.rows[0].active) return res.status(409).json({ error: 'Cannot delete an active set' });

        await query(`DELETE FROM ${type} WHERE id = $1`, [id], 'references');
        res.json({ deleted: true });
    } catch (err) {
        console.error('[PARAMS] Error deleting set:', err.message);
        res.status(500).json({ error: 'Internal server error' });
    }
});

/**
 * PUT /params/sets/:id/version?type=sensors
 * Incrementa la versione (bump)
 */
router.put('/sets/:id/version', async (req, res) => {
    const { type } = req.query;
    const { id } = req.params;
    const { bump } = req.body; // 'major', 'minor', 'patch'
    if (!type || !sets.includes(type))
        return res.status(400).json({ error: 'type parameter invalid' });

    const field = bump === 'major' ? 'mayor' : bump === 'minor' ? 'minor' : 'patch';
    const resets = bump === 'major' ? ', minor = 0, patch = 0' : bump === 'minor' ? ', patch = 0' : '';

    try {
        const result = await query(
            `UPDATE ${type} SET ${field} = ${field} + 1 ${resets}, updated_at = NOW() WHERE id = $1 RETURNING *`,
            [id], 'references'
        );
        if (!result.rows[0]) return res.status(404).json({ error: 'Set not found' });
        res.json(result.rows[0]);
    } catch (err) {
        console.error('[PARAMS] Error bumping version:', err.message);
        res.status(500).json({ error: 'Internal server error' });
    }
});

module.exports = router;
