// PRE Web GUI — Trigger routes (event triggers + webhooks)
const { Router } = require('express');
const triggerSystem = require('../triggers');

const router = Router();

router.get('/triggers', (_req, res) => {
  const triggers = triggerSystem.loadTriggers();
  const enriched = triggers.map(t => ({
    ...t,
    watching: triggerSystem.isWatching ? triggerSystem.isWatching(t.id) : false,
  }));
  res.json(enriched);
});

router.post('/triggers', (req, res) => {
  const result = triggerSystem.trigger({ action: 'add', ...req.body });
  if (result.startsWith('Error')) return res.status(400).json({ error: result });
  res.json({ ok: true, message: result });
});

router.patch('/triggers/:id', (req, res) => {
  const action = req.body.enabled === false ? 'disable' : 'enable';
  const result = triggerSystem.trigger({ action, id: req.params.id });
  if (result.startsWith('Error')) return res.status(400).json({ error: result });
  res.json({ ok: true, message: result });
});

router.post('/triggers/:id/restart', (req, res) => {
  const result = triggerSystem.restartWatcher(req.params.id);
  if (result.error) return res.status(400).json({ error: result.error });
  res.json(result);
});

router.delete('/triggers/:id', (req, res) => {
  const result = triggerSystem.trigger({ action: 'remove', id: req.params.id });
  if (result.startsWith('Error')) return res.status(404).json({ error: result });
  res.json({ ok: true, message: result });
});

// Webhook endpoint — external services POST here to fire triggers
router.post('/triggers/webhook/:id', (req, res) => {
  const result = triggerSystem.handleWebhook(req.params.id, {
    body: req.body,
    headers: req.headers,
    rawBody: req.rawBody,
    ip: req.ip,
  });
  if (result.error) return res.status(result.status || 400).json({ error: result.error });
  res.json(result);
});

module.exports = router;
