const router = require('express').Router();
const db = require('../store/db');
const { createConnectionToken } = require('../store/redis');
const crypto = require('crypto');

/**
 * Aggiunge un nuovo sensore autorizzato a partire da un nome univoco e un codice che verrà salvato in forma hashata.
 */
router.post('/new', async (req, res) => {
    const { name, code } = req.body;

    if (!name || !code) {
        return res.status(400).json({ error: 'name and code are required' });
    }

    if (code.length < 6) {
        return res.status(400).json({ error: 'code must be at least 6 characters' });
    }

    const salt = crypto.randomBytes(16).toString('hex');
    const hash = crypto.scryptSync(code, salt, 64).toString('hex');
    const codeHash = `${salt}:${hash}`;

    try {
        await db.query('sensors',
            'INSERT INTO sensors (name, code_hash) VALUES ($1, $2)',
            [name, codeHash]
        );
        res.status(201).json({ status: 'ok' });
    } catch (err) {
        if (err.code === '23505') {
            return res.status(409).json({ error: 'name already exists' });
        }
        console.error('Error creating sensor', err);
        res.status(500).json({ error: `internal server error, ${err}` });
    }
});

router.post('/', async (req, res) => {
    const { name, code } = req.body;

    if (!name || !code) {
        return res.status(400).json({ error: 'name and code required' });
    }

    try {
        const result = await db.query('sensors',
            'SELECT code_hash FROM sensors WHERE name = $1',
            [name]
        );

        if (result.rows.length === 0) {
            return res.status(401).json({ error: 'invalid name or code' });
        }

        const [salt, storedHash] = result.rows[0].code_hash.split(':');
        const hash = crypto.scryptSync(code, salt, 64).toString('hex');

        if (hash !== storedHash) {
            return res.status(401).json({ error: 'invalid name or code' });
        }
        const token = await createConnectionToken(name);

        res.status(200).json({ s: 'ok', t: token });
    } catch (err) {
        console.error('Error verifying connection', err);
        res.status(500).json({ error: `internal server error, ${err}` });
    }
});

module.exports = router;
