const { getDatabase } = require('../config/database');

async function getStats(req, res) {
    try {
        const db = getDatabase();
        const now = Date.now();
        const fifteenMin = 15 * 60 * 1000;

        // Agents
        const agents = db.prepare('SELECT hostname, last_checkin, cpu_usage_percent, ram_total_gb, ram_used_gb, bitlocker_status FROM monitoring_agents').all();
        const agentList = agents.map(a => {
            const ms = a.last_checkin ? new Date(a.last_checkin + (a.last_checkin.includes('Z') ? '' : 'Z')).getTime() : 0;
            const ram_usage_percent = a.ram_total_gb > 0 ? Math.round((a.ram_used_gb / a.ram_total_gb) * 100) : 0;
            return { ...a, ram_usage_percent, online: ms && (now - ms) < fifteenMin };
        });
        const online = agentList.filter(a => a.online).length;

        // Tickets
        const ticketStats = db.prepare(`
            SELECT
                COUNT(*) as total,
                SUM(CASE WHEN status NOT IN ('closed','resolved') THEN 1 ELSE 0 END) as open,
                SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as inProgress,
                SUM(CASE WHEN date(created_at) = date('now') AND status IN ('closed','resolved') THEN 1 ELSE 0 END) as closedToday,
                SUM(CASE WHEN priority = 'critical' AND status NOT IN ('closed','resolved') THEN 1 ELSE 0 END) as critical,
                SUM(CASE WHEN priority = 'high' AND status NOT IN ('closed','resolved') THEN 1 ELSE 0 END) as high,
                SUM(CASE WHEN priority = 'medium' AND status NOT IN ('closed','resolved') THEN 1 ELSE 0 END) as medium,
                SUM(CASE WHEN priority = 'low' AND status NOT IN ('closed','resolved') THEN 1 ELSE 0 END) as low
            FROM tickets
        `).get();

        // Patch overview
        const patchStats = db.prepare(`
            SELECT
                COUNT(*) as total,
                SUM(CASE WHEN windows_updates_pending = 0 THEN 1 ELSE 0 END) as compliant,
                SUM(CASE WHEN windows_updates_pending > 0 THEN 1 ELSE 0 END) as warnings,
                SUM(COALESCE(windows_updates_pending, 0)) as total_pending_updates
            FROM monitoring_agents
        `).get();

        // Last security report
        const lastSecReport = db.prepare('SELECT * FROM security_reports ORDER BY created_at DESC LIMIT 1').get();

        // Ticket trend last 7 days
        const perDay7 = db.prepare(`
            SELECT date(created_at) as day, COUNT(*) as count
            FROM tickets
            WHERE created_at >= date('now', '-7 days')
            GROUP BY date(created_at)
            ORDER BY day ASC
        `).all();

        res.json({
            status: 'success',
            data: {
                agentList: agentList.map(a => ({
                    hostname: a.hostname,
                    last_checkin: a.last_checkin,
                    cpu_usage_percent: a.cpu_usage_percent,
                    ram_usage_percent: a.ram_usage_percent,
                    bitlocker_status: a.bitlocker_status,
                })),
                monitoring: { total: agents.length, online, offline: agents.length - online },
                tickets: ticketStats,
                patch: patchStats,
                lastSecReport: lastSecReport || null,
                ticketMetrics: { perDay7: perDay7.map(r => r.count) },
            },
        });
    } catch (err) {
        res.status(500).json({ status: 'error', message: err.message });
    }
}

module.exports = { getStats };
