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

class NetworkDevice {
    static getAll() {
        const db = getDatabase();
        return db.prepare(`SELECT * FROM network_devices ORDER BY type, name`).all();
    }

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

    static getEnabled() {
        const db = getDatabase();
        return db.prepare(`SELECT * FROM network_devices WHERE enabled = 1`).all();
    }

    static create(data) {
        const db = getDatabase();
        const result = db.prepare(`
            INSERT INTO network_devices (name, type, host, check_type, port, http_path, http_keyword,
                snmp_community, snmp_version, interval_sec, timeout_sec, enabled, notify_email, location)
            VALUES (@name, @type, @host, @check_type, @port, @http_path, @http_keyword,
                @snmp_community, @snmp_version, @interval_sec, @timeout_sec, @enabled, @notify_email, @location)
        `).run(data);
        return this.getById(result.lastInsertRowid);
    }

    static update(id, data) {
        const db = getDatabase();
        db.prepare(`
            UPDATE network_devices SET
                name = @name, type = @type, host = @host, check_type = @check_type,
                port = @port, http_path = @http_path, http_keyword = @http_keyword,
                snmp_community = @snmp_community, snmp_version = @snmp_version,
                interval_sec = @interval_sec, timeout_sec = @timeout_sec,
                enabled = @enabled, notify_email = @notify_email, location = @location
            WHERE id = @id
        `).run({ ...data, id });
        return this.getById(id);
    }

    static updateStatus(id, status, rtt_ms) {
        const db = getDatabase();
        db.prepare(`
            UPDATE network_devices SET last_status = ?, last_checked = datetime('now'), last_rtt_ms = ?
            WHERE id = ?
        `).run(status, rtt_ms ?? null, id);
    }

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

    static addCheck(deviceId, status, rtt_ms, error_msg) {
        const db = getDatabase();
        db.prepare(`
            INSERT INTO device_checks (device_id, status, rtt_ms, error_msg)
            VALUES (?, ?, ?, ?)
        `).run(deviceId, status, rtt_ms ?? null, error_msg ?? null);
    }

    static getChecks(deviceId, hoursBack = 24) {
        const db = getDatabase();
        return db.prepare(`
            SELECT status, rtt_ms, error_msg, checked_at
            FROM device_checks
            WHERE device_id = ? AND checked_at >= datetime('now', '-' || ? || ' hours')
            ORDER BY checked_at ASC
        `).all(deviceId, hoursBack);
    }

    static getUptimeStats(deviceId, hoursBack = 24) {
        const db = getDatabase();
        const row = db.prepare(`
            SELECT
                COUNT(*) as total,
                SUM(CASE WHEN status = 'up' THEN 1 ELSE 0 END) as up_count
            FROM device_checks
            WHERE device_id = ? AND checked_at >= datetime('now', '-' || ? || ' hours')
        `).get(deviceId, hoursBack);
        const pct = row.total > 0 ? Math.round((row.up_count / row.total) * 100 * 10) / 10 : null;
        return { up: row.up_count, total: row.total, pct };
    }

    static getStatistics() {
        const db = getDatabase();
        const all = db.prepare(`SELECT last_status FROM network_devices`).all();
        const total = all.length;
        const up = all.filter(d => d.last_status === 'up').length;
        const down = all.filter(d => d.last_status === 'down').length;
        const unknown = all.filter(d => d.last_status === 'unknown').length;
        return { total, up, down, unknown };
    }

    static cleanupOldChecks() {
        const db = getDatabase();
        db.prepare(`DELETE FROM device_checks WHERE checked_at < datetime('now', '-7 days')`).run();
    }
}

module.exports = NetworkDevice;
