const express = require('express');
const router = express.Router();
const { authenticateToken } = require('../middleware/auth');
const { requireSuperAdmin } = require('../middleware/roleCheck');
const { asyncHandler } = require('../middleware/errorHandler');
const Database = require('better-sqlite3');
const DB_PATH = process.env.DATABASE_PATH || './database.sqlite';

router.use(authenticateToken);
router.use(requireSuperAdmin);

// Alle Cronjob-Definitionen (statisch)
const CRON_JOBS = [
    { name: 'entra_profile_sync', label: 'Entra Profil-Sync', description: 'Synchronisiert Profildaten und Fotos aus Azure AD', schedule: 'Täglich 02:00 Uhr', icon: '👤', canRun: true },
    { name: 'imap_ticket_import', label: 'E-Mail Ticket-Import', description: 'Importiert eingehende E-Mails als Tickets', schedule: 'Alle 30 Sekunden', icon: '📧', canRun: false },
    { name: 'mdo_alert_poll', label: 'MDO Alert-Polling', description: 'Holt neue Security-Alerts aus Microsoft Defender', schedule: 'Alle 5 Minuten', icon: '🛡️', canRun: false },
    { name: 'proxmox_sync', label: 'Proxmox Sync', description: 'Synchronisiert VM/CT-Status von Proxmox', schedule: 'Alle 5 Minuten', icon: '🖥️', canRun: false },
    { name: 'monitoring_status', label: 'Monitoring Status', description: 'Aktualisiert Online/Offline-Status der Agents', schedule: 'Kontinuierlich', icon: '📡', canRun: false },
    { name: 'health_history', label: 'Health-History', description: 'Zeichnet API- und DB-Status auf', schedule: 'Alle 5 Minuten', icon: '💚', canRun: false },
    { name: 'escalation_check', label: 'Eskalations-Check', description: 'Prüft überfällige Tickets und sendet Eskalations-Mails', schedule: 'Stündlich', icon: '🚨', canRun: false },
    { name: 'shares_cleanup', label: 'Shares-Cleanup', description: 'Löscht abgelaufene / verbrauchte sichere Links', schedule: 'Alle 15 Minuten', icon: '🔗', canRun: false },
    { name: 'stock_threshold_check', label: 'Mindestbestand-Check', description: 'Prüft Lagerbestände und sendet Warnungen', schedule: 'Täglich 07:00 Uhr', icon: '📦', canRun: false },
    { name: 'weekly_report', label: 'Wöchentlicher Bericht', description: 'Versendet den wöchentlichen Ticket-Report', schedule: 'Montag 08:00 Uhr', icon: '📊', canRun: false },
];

// GET /api/cron — alle Jobs mit letztem Log
router.get('/', asyncHandler(async (req, res) => {
    const db = new Database(DB_PATH);
    const jobs = CRON_JOBS.map(job => {
        const lastLog = db.prepare(`
            SELECT * FROM cron_logs WHERE job_name = ? ORDER BY started_at DESC LIMIT 1
        `).get(job.name);
        return { ...job, lastRun: lastLog || null };
    });
    db.close();
    res.json({ status: 'success', data: jobs });
}));

// GET /api/cron/:name/logs — Logs für einen Job
router.get('/:name/logs', asyncHandler(async (req, res) => {
    const db = new Database(DB_PATH);
    const logs = db.prepare(`
        SELECT * FROM cron_logs WHERE job_name = ? ORDER BY started_at DESC LIMIT 50
    `).all(req.params.name);
    db.close();
    res.json({ status: 'success', data: logs });
}));

// POST /api/cron/:name/run — Job manuell auslösen
router.post('/:name/run', asyncHandler(async (req, res) => {
    const { name } = req.params;
    if (name === 'entra_profile_sync') {
        const { syncEntraProfiles } = require('../services/entraSync.service');
        syncEntraProfiles().catch(console.error); // async, nicht awaiten
        return res.json({ status: 'success', message: 'Job gestartet' });
    }
    res.status(404).json({ status: 'error', message: 'Job nicht gefunden oder nicht manuell auslösbar' });
}));

module.exports = router;
