const express = require('express');
const { requireCapability } = require('../middleware/auth');
const { listAlerts, runAlertCycle, scanAlerts, setStatus, summary } = require('../services/alerts');
const { publicConfig, saveConfig, sendTestEmail } = require('../services/notifications');
const { sendTestWebhook } = require('../services/webhooks');
const { submitTicket } = require('../services/servicenow');

const router = express.Router();

router.get('/alerts', (req, res) => {
  res.json({ alerts: listAlerts({ ...req.query, entity_id: req.companyId }), summary: summary(req.companyId) });
});

router.post('/alerts/scan', requireCapability('alerts.manage'), (req, res) => {
  const result = scanAlerts(req.user.id);
  res.json({ created: result.created.length, openCount: result.openCount, alerts: listAlerts({ entity_id: req.companyId }), summary: summary(req.companyId) });
});

router.post('/alerts/run', requireCapability('admin.integrations'), async (req, res, next) => {
  try {
    res.json(await runAlertCycle(req.user.id));
  } catch (error) {
    next(error);
  }
});

router.put('/alerts/:id/acknowledge', requireCapability('alerts.manage'), (req, res) => {
  const alert = setStatus(req.params.id, 'acknowledged', req.user.id);
  if (!alert) return res.status(404).json({ error: 'Alert not found' });
  return res.json({ alert });
});

router.put('/alerts/:id/dismiss', requireCapability('alerts.manage'), (req, res) => {
  const alert = setStatus(req.params.id, 'dismissed', req.user.id);
  if (!alert) return res.status(404).json({ error: 'Alert not found' });
  return res.json({ alert });
});

router.post('/alerts/:id/ticket', requireCapability('alerts.manage'), async (req, res, next) => {
  try {
    const ticket = await submitTicket(req.params.id, req.user.id);
    if (!ticket) return res.status(404).json({ error: 'Alert not found' });
    return res.json({ ticket });
  } catch (error) {
    next(error);
  }
});

router.get('/notifications/settings', requireCapability('admin.integrations'), (req, res) => {
  res.json({ settings: publicConfig() });
});

router.put('/notifications/settings', requireCapability('admin.integrations'), (req, res) => {
  res.json({ settings: saveConfig(req.body, req.user.id) });
});

router.post('/notifications/test', requireCapability('admin.integrations'), async (req, res, next) => {
  try {
    res.json(await sendTestEmail(req.body.to, req.user.id));
  } catch (error) {
    next(error);
  }
});

router.post('/notifications/webhook-test', requireCapability('admin.integrations'), async (req, res, next) => {
  try {
    res.json(await sendTestWebhook(req.user.id));
  } catch (error) {
    next(error);
  }
});

module.exports = router;
