-- 018_patch_management.sql: Patch management system

CREATE TABLE IF NOT EXISTS patch_status (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    device_uid      TEXT NOT NULL REFERENCES devices(device_uid) ON DELETE CASCADE,
    kb_id           TEXT NOT NULL,
    title           TEXT NOT NULL,
    severity        TEXT,
    is_installed    INTEGER NOT NULL DEFAULT 0,
    discovered_at   TEXT NOT NULL DEFAULT (datetime('now')),
    installed_at    TEXT,
    updated_at      TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(device_uid, kb_id)
);

CREATE TABLE IF NOT EXISTS patch_policies (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    target_type     TEXT NOT NULL DEFAULT 'global' CHECK(target_type IN ('global', 'device', 'group')),
    target_id       TEXT,
    auto_approve    INTEGER NOT NULL DEFAULT 0,
    severity_filter TEXT NOT NULL DEFAULT 'important',
    enabled         INTEGER NOT NULL DEFAULT 1,
    created_at      TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at      TEXT NOT NULL DEFAULT (datetime('now'))
);

-- Behavior metrics for anomaly detection
CREATE TABLE IF NOT EXISTS behavior_metrics (
    id                  INTEGER PRIMARY KEY AUTOINCREMENT,
    device_uid          TEXT NOT NULL REFERENCES devices(device_uid) ON DELETE CASCADE,
    clipboard_ops_count INTEGER NOT NULL DEFAULT 0,
    clipboard_ops_night INTEGER NOT NULL DEFAULT 0,
    print_jobs_count    INTEGER NOT NULL DEFAULT 0,
    usb_file_ops_count  INTEGER NOT NULL DEFAULT 0,
    new_processes_count INTEGER NOT NULL DEFAULT 0,
    period_secs         INTEGER NOT NULL DEFAULT 3600,
    reported_at         TEXT NOT NULL DEFAULT (datetime('now'))
);

-- Anomaly alerts generated by the detection engine
CREATE TABLE IF NOT EXISTS anomaly_alerts (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    device_uid      TEXT NOT NULL REFERENCES devices(device_uid) ON DELETE CASCADE,
    anomaly_type    TEXT NOT NULL,
    severity        TEXT NOT NULL DEFAULT 'medium' CHECK(severity IN ('low', 'medium', 'high', 'critical')),
    detail          TEXT NOT NULL,
    metric_value    REAL,
    baseline_value  REAL,
    handled         INTEGER NOT NULL DEFAULT 0,
    handled_by      TEXT,
    handled_at      TEXT,
    triggered_at    TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_patch_status_device ON patch_status(device_uid);
CREATE INDEX IF NOT EXISTS idx_patch_status_severity ON patch_status(severity, is_installed);
CREATE INDEX IF NOT EXISTS idx_behavior_metrics_device_time ON behavior_metrics(device_uid, reported_at);
CREATE INDEX IF NOT EXISTS idx_anomaly_alerts_device ON anomaly_alerts(device_uid);
CREATE INDEX IF NOT EXISTS idx_anomaly_alerts_unhandled ON anomaly_alerts(handled) WHERE handled = 0;
