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

class MonitoringAgent {
    static getAll() {
        const db = getDatabase();
        return db.prepare(`
            SELECT * FROM monitoring_agents ORDER BY hostname ASC
        `).all();
    }

    static getById(id) {
        const db = getDatabase();
        return db.prepare('SELECT * FROM monitoring_agents WHERE id = ?').get(id);
    }

    static getByHostname(hostname) {
        const db = getDatabase();
        return db.prepare('SELECT * FROM monitoring_agents WHERE hostname = ?').get(hostname);
    }

    static upsert(data) {
        const db = getDatabase();
        const existing = this.getByHostname(data.hostname);

        if (existing) {
            db.prepare(`
                UPDATE monitoring_agents SET
                    ip_address = ?, mac_address = ?, os_name = ?, os_version = ?,
                    cpu_model = ?, cpu_cores = ?, cpu_usage_percent = ?,
                    ram_total_gb = ?, ram_used_gb = ?,
                    disk_total_gb = ?, disk_free_gb = ?,
                    last_user = ?, uptime_hours = ?, domain = ?,
                    agent_version = ?, installed_software = ?,
                    windows_updates_pending = ?,
                    tpm_present = ?, tpm_version = ?, tpm_v2 = ?,
                    secure_boot = ?, win11_ready = ?,
                    bitlocker_status = ?, defender_enabled = ?,
                    defender_signatures_age = ?, hardware_serial = ?,
                    status = 'online',
                    last_checkin = CURRENT_TIMESTAMP,
                    updated_at = CURRENT_TIMESTAMP
                WHERE hostname = ?
            `).run(
                data.ip_address || null,
                data.mac_address || null,
                data.os_name || data.os || null,
                data.os_version || null,
                data.cpu_model || null,
                data.cpu_cores || null,
                data.cpu_usage_percent != null ? parseFloat(data.cpu_usage_percent) : (data.cpu_usage != null ? parseFloat(data.cpu_usage) : null),
                data.ram_total_gb != null ? parseFloat(data.ram_total_gb) : (data.ram_total != null ? parseFloat(data.ram_total) : null),
                data.ram_used_gb != null ? parseFloat(data.ram_used_gb) : (data.ram_used != null ? parseFloat(data.ram_used) : null),
                data.disk_total_gb != null ? parseFloat(data.disk_total_gb) : (data.disk_total != null ? parseFloat(data.disk_total) : null),
                data.disk_free_gb != null ? parseFloat(data.disk_free_gb) : (data.disk_free != null ? parseFloat(data.disk_free) : null),
                data.last_user || null,
                data.uptime_hours != null ? parseFloat(data.uptime_hours) : null,
                data.domain || null,
                data.agent_version || null,
                data.installed_software ? JSON.stringify(data.installed_software) : null,
                data.windows_updates_pending != null ? parseInt(data.windows_updates_pending) : (data.pending_updates != null ? parseInt(data.pending_updates) : 0),
                data.tpm_present ? 1 : 0, data.tpm_version || null, data.tpm_v2 ? 1 : 0,
                data.secure_boot ? 1 : 0, data.win11_ready ? 1 : 0,
                data.bitlocker_status || 'unknown',
                data.defender_enabled ? 1 : 0,
                data.defender_signatures_age != null ? parseInt(data.defender_signatures_age) : -1,
                data.hardware_serial || null,
                data.hostname
            );
            return this.getByHostname(data.hostname);
        } else {
            const result = db.prepare(`
                INSERT INTO monitoring_agents (
                    hostname, ip_address, mac_address, os_name, os_version,
                    cpu_model, cpu_cores, cpu_usage_percent,
                    ram_total_gb, ram_used_gb, disk_total_gb, disk_free_gb,
                    last_user, uptime_hours, domain, agent_version,
                    installed_software, windows_updates_pending,
                    tpm_present, tpm_version, tpm_v2, secure_boot, win11_ready,
                    bitlocker_status, defender_enabled, defender_signatures_age, hardware_serial
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            `).run(
                data.hostname,
                data.ip_address || null,
                data.mac_address || null,
                data.os_name || data.os || null,
                data.os_version || null,
                data.cpu_model || null,
                data.cpu_cores || null,
                data.cpu_usage_percent != null ? parseFloat(data.cpu_usage_percent) : (data.cpu_usage != null ? parseFloat(data.cpu_usage) : null),
                data.ram_total_gb != null ? parseFloat(data.ram_total_gb) : (data.ram_total != null ? parseFloat(data.ram_total) : null),
                data.ram_used_gb != null ? parseFloat(data.ram_used_gb) : (data.ram_used != null ? parseFloat(data.ram_used) : null),
                data.disk_total_gb != null ? parseFloat(data.disk_total_gb) : (data.disk_total != null ? parseFloat(data.disk_total) : null),
                data.disk_free_gb != null ? parseFloat(data.disk_free_gb) : (data.disk_free != null ? parseFloat(data.disk_free) : null),
                data.last_user || null,
                data.uptime_hours != null ? parseFloat(data.uptime_hours) : null,
                data.domain || null,
                data.agent_version || null,
                data.installed_software ? JSON.stringify(data.installed_software) : null,
                data.windows_updates_pending != null ? parseInt(data.windows_updates_pending) : (data.pending_updates != null ? parseInt(data.pending_updates) : 0),
                data.tpm_present ? 1 : 0, data.tpm_version || null, data.tpm_v2 ? 1 : 0,
                data.secure_boot ? 1 : 0, data.win11_ready ? 1 : 0,
                data.bitlocker_status || 'unknown',
                data.defender_enabled ? 1 : 0,
                data.defender_signatures_age != null ? parseInt(data.defender_signatures_age) : -1,
                data.hardware_serial || null
            );
            return this.getById(result.lastInsertRowid);
        }
    }

    static markOffline() {
        const db = getDatabase();
        // Mark agents offline if no checkin in last 15 minutes
        db.prepare(`
            UPDATE monitoring_agents
            SET status = 'offline'
            WHERE status = 'online'
              AND last_checkin < datetime('now', '-15 minutes')
        `).run();
    }

    static delete(id) {
        const db = getDatabase();
        return db.prepare('DELETE FROM monitoring_agents WHERE id = ?').run(id).changes > 0;
    }

    static getStatistics() {
        const db = getDatabase();
        const total = db.prepare('SELECT COUNT(*) as c FROM monitoring_agents').get().c;
        const online = db.prepare("SELECT COUNT(*) as c FROM monitoring_agents WHERE status = 'online'").get().c;
        const offline = db.prepare("SELECT COUNT(*) as c FROM monitoring_agents WHERE status = 'offline'").get().c;
        const highCpu = db.prepare("SELECT COUNT(*) as c FROM monitoring_agents WHERE cpu_usage_percent > 80 AND status = 'online'").get().c;
        const lowDisk = db.prepare("SELECT COUNT(*) as c FROM monitoring_agents WHERE disk_free_gb < 10 AND status = 'online'").get().c;
        return { total, online, offline, highCpu, lowDisk };
    }
}

module.exports = MonitoringAgent;
