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

router.get('/', (req, res) => {
  const channels = db.prepare('SELECT * FROM tg_channels ORDER BY id DESC').all();
  res.render('admin/channels', { channels });
});

router.post('/', (req, res) => {
  const { name, chat_id, notes } = req.body;
  if (!name || !chat_id) return res.redirect('/admin/channels');
  db.prepare('INSERT INTO tg_channels (name, chat_id, notes) VALUES (?, ?, ?)').run(name, chat_id, notes || null);
  res.redirect('/admin/channels');
});

router.post('/:id/toggle', (req, res) => {
  db.prepare('UPDATE tg_channels SET enabled = NOT enabled WHERE id = ?').run(req.params.id);
  res.redirect('/admin/channels');
});

router.post('/:id/delete', (req, res) => {
  db.prepare('DELETE FROM tg_channels WHERE id = ?').run(req.params.id);
  res.redirect('/admin/channels');
});

module.exports = router;
