const ExternalAlert = require('../models/ExternalAlert');
const Ticket = require('../models/Ticket');

const getAll = (req, res) => {
    try {
        const acknowledged = req.query.acknowledged !== undefined
            ? req.query.acknowledged === 'true'
            : undefined;
        const alerts = ExternalAlert.getAll({ acknowledged });
        res.json({ status: 'success', data: alerts });
    } catch (err) {
        res.status(500).json({ status: 'error', message: err.message });
    }
};

const acknowledge = (req, res) => {
    try {
        const alert = ExternalAlert.acknowledge(req.params.id);
        if (!alert) return res.status(404).json({ status: 'error', message: 'Alert nicht gefunden' });
        res.json({ status: 'success', data: alert });
    } catch (err) {
        res.status(500).json({ status: 'error', message: err.message });
    }
};

const createTicket = (req, res) => {
    try {
        const alert = ExternalAlert.getById(req.params.id);
        if (!alert) return res.status(404).json({ status: 'error', message: 'Alert nicht gefunden' });

        const priorityMap = { CRIT: 'kritisch', WARN: 'hoch', OK: 'niedrig', UNKNOWN: 'mittel' };

        const title = alert.device
            ? `[${alert.source?.toUpperCase()}] ${alert.device} – ${alert.message || alert.state_transition}`.substring(0, 200)
            : (alert.message || 'Monitoring Alert').substring(0, 200);

        const description = [
            alert.device     ? `**Gerät:** ${alert.device}` : '',
            alert.service    ? `**Service:** ${alert.service}` : '',
            alert.state_transition ? `**Status:** ${alert.state_transition}` : '',
            alert.severity   ? `**Severity:** ${alert.severity}` : '',
            alert.message    ? `\n**Meldung:** ${alert.message}` : '',
            alert.customer   ? `**Kunde:** ${alert.customer}` : '',
            alert.monitored_by ? `**Überwacht von:** ${alert.monitored_by}` : '',
            alert.state_time ? `**Zeitpunkt:** ${alert.state_time}` : '',
        ].filter(Boolean).join('\n');

        const ticket = Ticket.create({
            title,
            description,
            source: 'monitoring',
            category: 'Netzwerk',
            priority: priorityMap[alert.severity] || 'mittel',
            status: 'offen',
        });

        ExternalAlert.setTicket(alert.id, ticket.id);
        res.json({ status: 'success', data: { ticket, alert: ExternalAlert.getById(alert.id) } });
    } catch (err) {
        res.status(500).json({ status: 'error', message: err.message });
    }
};

const remove = (req, res) => {
    try {
        ExternalAlert.delete(req.params.id);
        res.json({ status: 'success' });
    } catch (err) {
        res.status(500).json({ status: 'error', message: err.message });
    }
};

module.exports = { getAll, acknowledge, createTicket, remove };
