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

router.use((req, res, next) => {
  if (!req.session.user_id) return res.status(401).json({ error: 'Unauthorized' });
  next();
});

router.get('/', async (req, res) => {
  try {
    const rows = await db.query('SELECT id, name, status FROM workflows ORDER BY name');
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/', async (req, res) => {
  try {
    const insertId = await db.insert('INSERT INTO workflows (name, status) VALUES (?, ?)', [req.body.name, req.body.status || 'active']);
    res.json({ id: insertId, success: true });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.delete('/:id', async (req, res) => {
  try {
    await db.query('DELETE FROM workflows WHERE id = ?', [req.params.id]);
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;
