/**
 * Parser für Netgo Monitoring-Emails
 * Erkennt und parst strukturierte Alert-Emails von monitoring@mg.netgo.de
 */

const NETGO_DOMAINS = ['netgo.de', 'mg.netgo.de'];

function isNetgoMonitoringEmail(fromEmail) {
    const addr = (fromEmail || '').toLowerCase();
    return NETGO_DOMAINS.some(d => addr.endsWith('@' + d) || addr.includes('@' + d));
}

/**
 * Extrahiert einen Wert aus dem Email-Body.
 * Unterstützt "Label: Value" und "Label\nValue"-Formate.
 */
function extractField(body, label) {
    // Format: "Label: Value" (selbe Zeile)
    const inlineMatch = body.match(new RegExp(label + ':\\s*([^\\n]+)', 'i'));
    if (inlineMatch) return inlineMatch[1].trim();

    // Format: "Label\nValue" (nächste Zeile)
    const nextLineMatch = body.match(new RegExp(label + '\\s*\\n([^\\n]+)', 'i'));
    if (nextLineMatch) return nextLineMatch[1].trim();

    return '';
}

/**
 * Parst eine Netgo-Monitoring-Email und gibt ein strukturiertes Objekt zurück.
 * Gibt null zurück wenn es keine Netgo-Email ist.
 */
function parseNetgoAlert(fromEmail, subject, body) {
    if (!isNetgoMonitoringEmail(fromEmail)) return null;

    const text = body || '';

    // Device
    const device = extractField(text, 'Device');

    // Customer
    const customer = extractField(text, 'Customer');

    // Service – steht nach "Service Summary\nService\n[Name]" oder "Service: [Name]"
    let service = extractField(text, 'Service');
    // Manchmal gibt es "Service Summary" gefolgt von "Service\n[Name]"
    if (!service || service.toLowerCase() === 'summary') {
        const svcMatch = text.match(/Service\s+Summary\s*\n\s*Service\s*\n([^\n]+)/i);
        if (svcMatch) service = svcMatch[1].trim();
    }

    // State Transition (z.B. "Normal to Failed", "Failed to Normal")
    const stateTransition = extractField(text, 'State Transition');

    // Severity: CRIT, WARN, OK, WARNING, CRITICAL
    const sevMatch = text.match(/\b(CRIT|CRITICAL|WARN|WARNING|OK|RECOVERY)\b/i);
    let severity = sevMatch ? sevMatch[1].toUpperCase() : '';
    // Normalisieren
    if (severity === 'CRITICAL') severity = 'CRIT';
    if (severity === 'WARNING') severity = 'WARN';
    if (severity === 'RECOVERY') severity = 'OK';

    // Severity-Fallback aus State Transition ableiten
    if (!severity && stateTransition) {
        const st = stateTransition.toLowerCase();
        const toMatch = st.match(/\bto\s+(\w+)/);
        const stateTo = toMatch ? toMatch[1] : '';
        if (/normal|up|ok|resolved|recovered/.test(stateTo)) {
            severity = 'OK';
        } else if (/failed|down|unreachable|critical|unavailable|offline/.test(stateTo)) {
            severity = 'CRIT';
        } else if (/warning|degraded|slow|misconfigured/.test(stateTo)) {
            severity = 'WARN';
        } else {
            severity = 'UNKNOWN';
        }
    }
    if (!severity) severity = 'UNKNOWN';

    // Probe Message
    const message = extractField(text, 'Probe Message');

    // Monitored By
    const monitoredBy = extractField(text, 'Monitored By');

    // Time of State Transition
    let stateTime = extractField(text, 'Time of State Transition');
    if (!stateTime) stateTime = extractField(text, 'Time of State');

    // Fallback: aus Subject (z.B. "[CRIT] SERVER-DC02 - Service not running")
    if (!device && subject) {
        const subjectDeviceMatch = subject.match(/\b([A-Z][A-Z0-9\-_]{2,})\b/);
        if (subjectDeviceMatch) {
            // Use subject device only if no device found in body
        }
    }

    return {
        source: 'netgo',
        device: device || extractDeviceFromSubject(subject),
        service: service || '',
        state_transition: stateTransition,
        severity,
        message: message || subject || '',
        customer,
        monitored_by: monitoredBy,
        state_time: stateTime,
    };
}

function extractDeviceFromSubject(subject) {
    if (!subject) return '';
    // "[CRIT] SERVER-DC02 - ..." → "SERVER-DC02"
    const match = subject.match(/\]\s*([A-Z][A-Z0-9\-_]{2,})/);
    return match ? match[1] : '';
}

/**
 * Gibt zurück ob der Alert eine Entwarnung (Recovery) ist
 */
function isRecovery(alert) {
    if (!alert) return false;
    const st = (alert.state_transition || '').toLowerCase();
    if (alert.severity === 'OK') return true;
    // "XYZ to Normal" / "XYZ to Up" / etc.
    const toMatch = st.match(/\bto\s+(\w+)/);
    if (toMatch && /^(normal|up|ok|resolved|recovered)$/.test(toMatch[1])) return true;
    return st.includes('recovery') || st.includes('resolved');
}

module.exports = { parseNetgoAlert, isNetgoMonitoringEmail, isRecovery };
