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

// Get all positions
router.get('/', (req, res) => {
  db.all('SELECT * FROM positions ORDER BY display_order ASC', [], (err, rows) => {
    if (err) return res.status(500).json({ error: err.message });
    res.json(rows);
  });
});

// Create a new position
router.post('/', (req, res) => {
  const { title, display_order } = req.body;
  db.run(
    'INSERT INTO positions (title, display_order) VALUES (?, ?)',
    [title, display_order || 0],
    function(err) {
      if (err) return res.status(500).json({ error: err.message });
      res.json({ id: this.lastID, title, display_order: display_order || 0 });
    }
  );
});

// Delete a position (and potentially its candidates/votes - for simplicity keeping it basic)
router.delete('/:id', (req, res) => {
  const { id } = req.params;
  db.run('DELETE FROM positions WHERE id = ?', [id], function(err) {
    if (err) return res.status(500).json({ error: err.message });
    res.json({ message: 'Position deleted' });
  });
});

module.exports = router;
