import { Router } from 'express';
import { getCategories, toggleCategory, assignRules, addCategory, deleteCategory } from '../services/policyEngine.js';

const router = Router();

router.get('/', async (req, res) => {
  try {
    const categories = await getCategories();
    res.json(categories);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/:category/toggle', async (req, res) => {
  try {
    const { category } = req.params;
    const { allowed } = req.body;
    if (typeof allowed !== 'boolean') {
      return res.status(400).json({ error: '"allowed" must be a boolean' });
    }
    const results = await toggleCategory(decodeURIComponent(category), allowed);
    res.json({ category, allowed, results });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.put('/:category/rules', (req, res) => {
  try {
    const { category } = req.params;
    const { ruleIds } = req.body;
    if (!Array.isArray(ruleIds)) {
      return res.status(400).json({ error: '"ruleIds" must be an array' });
    }
    const result = assignRules(decodeURIComponent(category), ruleIds);
    res.json(result);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/', (req, res) => {
  try {
    const { name, icon } = req.body;
    if (!name) return res.status(400).json({ error: '"name" is required' });
    const result = addCategory(name, icon);
    res.json(result);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

router.delete('/:category', (req, res) => {
  try {
    deleteCategory(decodeURIComponent(req.params.category));
    res.json({ success: true });
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

export default router;
