const Risk = require('../models/Risk');
const { getSecureScore, getRiskyUsers, getDefenderAlerts, getNonCompliantDevices, getUsersWithoutMfa } = require('../services/graph.service');

exports.getAll = (req, res) => {
    const data = Risk.getAll(req.query);
    res.json({ success: true, data });
};

exports.getStats = (req, res) => {
    res.json({ success: true, data: Risk.getStats() });
};

exports.create = (req, res) => {
    const risk = Risk.create(req.body);
    res.status(201).json({ success: true, data: risk });
};

exports.update = (req, res) => {
    const risk = Risk.update(req.params.id, req.body);
    if (!risk) return res.status(404).json({ success: false, message: 'Nicht gefunden' });
    res.json({ success: true, data: risk });
};

exports.remove = (req, res) => {
    const ok = Risk.delete(req.params.id);
    if (!ok) return res.status(404).json({ success: false, message: 'Nicht gefunden' });
    res.json({ success: true });
};

exports.sync = async (req, res) => {
    const result = { created: 0, updated: 0, errors: [] };

    // 1. Secure Score
    try {
        const score = await getSecureScore();
        if (score) {
            const pct = Math.round((score.currentScore / score.maxScore) * 100);
            const prob = pct < 40 ? 5 : pct < 60 ? 4 : pct < 75 ? 3 : pct < 90 ? 2 : 1;
            const r = Risk.upsertAuto({
                source_type: 'secure_score',
                external_id: 'tenant_secure_score',
                title: `Microsoft Secure Score: ${pct}% (${Math.round(score.currentScore)}/${Math.round(score.maxScore)})`,
                description: `Aktueller Microsoft Secure Score. Je niedriger der Score, desto höher das Sicherheitsrisiko. Letzte Messung: ${new Date(score.createdDateTime).toLocaleDateString('de-DE')}.`,
                category: 'IT-Sicherheit',
                probability: prob,
                impact: 4,
            });
            result[r.last_synced ? 'updated' : 'created']++;
        }
    } catch (e) { result.errors.push(`Secure Score: ${e.message}`); }

    // 2. Risky Users (requires Azure AD Premium P2 - skip if not available)
    try {
        const users = await getRiskyUsers();
        for (const u of users) {
            const levelMap = { high: 5, medium: 3, low: 2 };
            const prob = levelMap[u.riskLevel] || 3;
            Risk.upsertAuto({
                source_type: 'risky_user',
                external_id: u.id,
                title: `Risikobehafteter Benutzer: ${u.userDisplayName || u.userPrincipalName}`,
                description: `Entra ID Identity Protection hat diesen Benutzer als risikoreich eingestuft. Risiko-Level: ${u.riskLevel}, Detail: ${u.riskDetail || 'unbekannt'}.`,
                category: 'Identität & Zugriff',
                probability: prob,
                impact: 4,
            });
        }
        result.created += users.length;
    } catch (e) {
        // Risky Users requires Azure AD Premium P2 – silently skip if not licensed
        if (!e.message.includes('Forbidden') && !e.message.includes('missing in the token')) {
            result.errors.push(`Risky Users: ${e.message}`);
        }
    }

    // 3. Defender Alerts
    try {
        const alerts = await getDefenderAlerts();
        const sevMap = { high: 5, medium: 3, low: 2, informational: 1 };
        for (const a of alerts) {
            Risk.upsertAuto({
                source_type: 'defender_alert',
                external_id: a.id,
                title: `Defender Alert: ${a.title}`,
                description: `${a.description || ''}`,
                category: 'Incident / Bedrohung',
                probability: sevMap[a.severity] || 3,
                impact: sevMap[a.severity] || 3,
                metadata: {
                    severity:    a.severity,
                    status:      a.status,
                    category:    a.category,
                    detected:    a.createdDateTime,
                    entities:    (a.evidence || []).map(e => e.userAccount?.displayName || e.deviceDnsName || e.fileName).filter(Boolean),
                    recommendation: a.recommendedActions,
                    alertWebUrl: a.alertWebUrl,
                },
            });
        }
        result.created += alerts.length;
    } catch (e) { result.errors.push(`Defender Alerts: ${e.message}`); }

    // 4. Non-Compliant Devices
    try {
        const devices = await getNonCompliantDevices();
        for (const d of devices) {
            Risk.upsertAuto({
                source_type: 'noncompliant_device',
                external_id: d.id,
                title: `Nicht-konformes Gerät: ${d.deviceName}`,
                description: `Gerät erfüllt die Intune-Compliance-Richtlinien nicht.`,
                category: 'Geräte & Endpunkte',
                probability: 3,
                impact: 3,
                metadata: {
                    deviceName:    d.deviceName,
                    user:          d.userDisplayName,
                    os:            d.operatingSystem,
                    serialNumber:  d.serialNumber,
                    lastSync:      d.lastSyncDateTime,
                },
            });
        }
        result.created += devices.length;
    } catch (e) { result.errors.push(`Non-Compliant Devices: ${e.message}`); }

    // 5. Users without MFA
    try {
        const noMfa = await getUsersWithoutMfa();
        if (noMfa.length > 0) {
            Risk.upsertAuto({
                source_type: 'no_mfa',
                external_id: 'users_without_mfa',
                title: `${noMfa.length} Benutzer ohne MFA registriert`,
                description: `${noMfa.length} Benutzer haben keine Multi-Faktor-Authentifizierung eingerichtet.`,
                category: 'Identität & Zugriff',
                probability: 4,
                impact: 4,
                metadata: {
                    users: noMfa.map(u => ({
                        name:  u.userDisplayName,
                        email: u.userPrincipalName,
                        mfaRegistered: u.isMfaRegistered,
                        methods: u.authMethods,
                    })),
                },
            });
            result.created++;
        }
    } catch (e) { result.errors.push(`MFA-Status: ${e.message}`); }

    res.json({ success: true, data: result });
};
