const router = require('express').Router();
const db = require('../store/db');

router.get('/', async (req, res) => {
    try {
        const result = await db.query('sensors', 'SELECT id, name FROM sensors');
        res.json(result.rows);
    } catch (err) {
        console.error('Error fetching sensors', err);
        res.status(500).json({ error: `internal server error, ${err}` });
    }
});

router.get('/:id', async (req, res) => {
    const { id } = req.params;
    try {
        const result = await db.query('sensors', 'SELECT id, name FROM sensors WHERE id = $1', [id]);
        if (result.rows.length === 0) {
            return res.status(404).json({ error: 'sensor not found' });
        }
        res.json(result.rows[0]);
    } catch (err) {
        console.error('Error fetching sensor', err);
        res.status(500).json({ error: `internal server error, ${err}` });
    }
});

//Toggle availability
router.post('/:id/inactive', async (req, res) => {
        const { id } = req.params;
        try {
            const result = await db.query('sensors', 'SELECT id, name FROM sensors WHERE id = $1', [id]);
            if (result.rows.length === 0) {
                return res.status(404).json({ error: 'sensor not found' });
            }
            await db.query('sensors', 'UPDATE sensors SET active = false WHERE id = $1', [id]);
            res.json({ status: 'ok' });
        } catch (err) {
            console.error('Error updating sensor status', err);
            res.status(500).json({ error: `internal server error, ${err}` });
        }
});

router.post('/:id/active', async (req, res) => {
    const { id } = req.params;
    try {
        const result = await db.query('sensors', 'SELECT id, name FROM sensors WHERE id = $1', [id]);
        if (result.rows.length === 0) {
            return res.status(404).json({ error: 'sensor not found' });
        }
        await db.query('sensors', 'UPDATE sensors SET active = true WHERE id = $1', [id]);
        res.json({ status: 'ok' });
    } catch (err) {
        console.error('Error updating sensor status', err);
        res.status(500).json({ error: `internal server error, ${err}` });
    }

});

module.exports = router;