/**
 * Parser für Arctic Wolf Security Alert Emails
 */

const ARCTIC_WOLF_DOMAINS = ['arcticwolf.com', 'notifications.arcticwolf.com'];

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

// Alle bekannten Sektions-Header als Trennzeichen
const SECTION_HEADERS = [
    'What is it\\?', 'Where is it\\?', 'When did it happen\\?',
    'Why does it matter\\?', 'How did Arctic Wolf detect this\\?',
    'What next steps should you take\\?', 'What does Arctic Wolf recommend',
    'Description', 'Incident name:',
];

// Bekannte Felder als Inline-Trennzeichen
const INLINE_FIELDS = [
    'Event type', 'Application', 'Process', 'User who ran the process',
    'Device name', 'Device IP address', 'When did it happen',
    'Incident name', 'Status', 'Ticket type',
];

/**
 * Extrahiert ein Key-Value-Feld. Stoppt am nächsten bekannten Feld.
 */
function extractField(body, label) {
    const stopPattern = INLINE_FIELDS
        .filter(n => n.toLowerCase() !== label.toLowerCase())
        .map(n => n.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
        .join('|');

    const re = new RegExp(label + ':\\s*(.+?)(?=\\n|' + stopPattern + '|$)', 'is');
    const m = body.match(re);
    if (m) return m[1].replace(/\s+/g, ' ').trim().substring(0, 200);
    return '';
}

/**
 * Extrahiert den Text einer freien Sektion bis zur nächsten Sektion.
 */
function extractSection(body, header) {
    const stop = SECTION_HEADERS
        .filter(h => h !== header.replace(/\?/g, '\\?'))
        .join('|');
    const re = new RegExp(header + '\\s*(.+?)(?=' + stop + '|$)', 'is');
    const m = body.match(re);
    if (!m) return '';
    return m[1].replace(/\s+/g, ' ').trim().substring(0, 800);
}

/**
 * Parst eine Arctic Wolf Email. Gibt null zurück wenn keine AW-Email.
 * raw_body wird als JSON mit allen strukturierten Feldern gespeichert.
 */
function parseArcticWolfAlert(fromEmail, subject, body) {
    if (!isArcticWolfEmail(fromEmail)) return null;

    const text = body || '';
    const subj = subject || '';

    // Severity aus Subject
    const sevMatch = subj.match(/\[(LOW|MEDIUM|HIGH|CRITICAL)\]/i);
    const severityLabel = sevMatch ? sevMatch[1].toUpperCase() : 'UNKNOWN';
    let severity = 'UNKNOWN';
    if (severityLabel === 'CRITICAL' || severityLabel === 'HIGH') severity = 'CRIT';
    else if (severityLabel === 'LOW' || severityLabel === 'MEDIUM') severity = 'WARN';

    // Incident-Name aus Subject
    const incidentName = subj.replace(/^\[(?:LOW|MEDIUM|HIGH|CRITICAL)\]\s*/i, '').trim();

    // Inline-Felder aus Description-Block
    const device    = extractField(text, 'Device name') || extractField(text, 'Device');
    const ip        = extractField(text, 'Device IP address') || extractField(text, 'IP address');
    const user      = extractField(text, 'User who ran the process') || extractField(text, 'User');
    const eventType = extractField(text, 'Event type');
    const app       = extractField(text, 'Application');
    const process_  = extractField(text, 'Process');
    const stateTime = extractField(text, 'When did it happen');

    // Freie Sektionen
    const whatIsIt    = extractSection(text, 'What is it\\?');
    const whyMatters  = extractSection(text, 'Why does it matter\\?');
    const howDetected = extractSection(text, 'How did Arctic Wolf detect this\\?');
    const nextSteps   = extractSection(text, 'What next steps should you take\\?');
    const recommend   = extractSection(text, 'What does Arctic Wolf recommend');

    // Service = Event type (für Übersichtskarte)
    const service = (eventType || app || 'Security Incident').substring(0, 100);

    // Kurze message für die Kartenvorschau
    const message = incidentName.substring(0, 200);

    // Alle Details als JSON in raw_body
    const structured = {
        severity_label: severityLabel,
        incident_name:  incidentName,
        event_type:     eventType,
        application:    app,
        process:        process_,
        user,
        ip,
        what_is_it:     whatIsIt,
        why_matters:    whyMatters,
        how_detected:   howDetected,
        next_steps:     nextSteps,
        recommend,
        when:           stateTime,
    };

    return {
        source:           'arcticwolf',
        device:           (device || 'Unknown').substring(0, 100),
        service,
        state_transition: `? -> ${severity}`,
        severity,
        message,
        customer:         'Cereda Systems GmbH',
        state_time:       stateTime || null,
        raw_body:         JSON.stringify(structured),
    };
}

module.exports = { parseArcticWolfAlert, isArcticWolfEmail };
