-- 004_alerts.sql: Alert system tables

CREATE TABLE IF NOT EXISTS alert_rules (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    name            TEXT NOT NULL,
    rule_type       TEXT NOT NULL CHECK(rule_type IN ('device_offline', 'cpu_high', 'memory_high', 'disk_high', 'usb_unauthorized', 'usb_unauth', 'asset_change')),
    condition       TEXT NOT NULL,
    severity        TEXT NOT NULL DEFAULT 'medium' CHECK(severity IN ('low', 'medium', 'high', 'critical')),
    enabled         INTEGER NOT NULL DEFAULT 1,
    notify_email    TEXT,
    notify_webhook  TEXT,
    created_at      TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at      TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS alert_records (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    rule_id         INTEGER REFERENCES alert_rules(id),
    device_uid      TEXT REFERENCES devices(device_uid) ON DELETE SET NULL,
    alert_type      TEXT NOT NULL,
    severity        TEXT NOT NULL DEFAULT 'medium' CHECK(severity IN ('low', 'medium', 'high', 'critical')),
    detail          TEXT NOT NULL,
    handled         INTEGER NOT NULL DEFAULT 0,
    handled_by      TEXT,
    handled_at      TEXT,
    triggered_at    TEXT NOT NULL DEFAULT (datetime('now'))
);

-- Admin audit log
CREATE TABLE IF NOT EXISTS admin_audit_log (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id         INTEGER NOT NULL REFERENCES users(id),
    action          TEXT NOT NULL,
    target_type     TEXT,
    target_id       TEXT,
    detail          TEXT,
    ip_address      TEXT,
    created_at      TEXT NOT NULL DEFAULT (datetime('now'))
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_alert_records_time ON alert_records(triggered_at);
CREATE INDEX IF NOT EXISTS idx_alert_records_device ON alert_records(device_uid, triggered_at);
CREATE INDEX IF NOT EXISTS idx_alert_records_unhandled ON alert_records(handled) WHERE handled = 0;
CREATE INDEX IF NOT EXISTS idx_audit_log_user_time ON admin_audit_log(user_id, created_at);
CREATE INDEX IF NOT EXISTS idx_audit_log_time ON admin_audit_log(created_at);
