-- 001_init.sql: Core tables (users, devices, device_status)

CREATE TABLE IF NOT EXISTS users (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    username    TEXT NOT NULL UNIQUE,
    password    TEXT NOT NULL,
    role        TEXT NOT NULL DEFAULT 'admin' CHECK(role IN ('admin', 'viewer')),
    created_at  TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS devices (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    device_uid      TEXT NOT NULL UNIQUE,
    hostname        TEXT NOT NULL,
    ip_address      TEXT NOT NULL,
    mac_address     TEXT,
    os_version      TEXT,
    client_version  TEXT,
    device_secret   TEXT,               -- HMAC key for message authentication
    status          TEXT NOT NULL DEFAULT 'offline' CHECK(status IN ('online', 'offline')),
    last_heartbeat  TEXT,
    registered_at   TEXT NOT NULL DEFAULT (datetime('now')),
    group_name      TEXT DEFAULT 'default'
);

CREATE TABLE IF NOT EXISTS device_status (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    device_uid      TEXT NOT NULL REFERENCES devices(device_uid) ON DELETE CASCADE,
    cpu_usage       REAL,
    memory_usage    REAL,
    memory_total_mb INTEGER,
    disk_usage      REAL,
    disk_total_mb   INTEGER,
    network_rx_rate INTEGER,
    network_tx_rate INTEGER,
    running_procs   INTEGER,
    top_processes   TEXT,
    reported_at     TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at      TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(device_uid)
);

CREATE TABLE IF NOT EXISTS device_status_history (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    device_uid      TEXT NOT NULL REFERENCES devices(device_uid) ON DELETE CASCADE,
    cpu_usage       REAL,
    memory_usage    REAL,
    disk_usage      REAL,
    network_rx_rate INTEGER,
    network_tx_rate INTEGER,
    running_procs   INTEGER,
    reported_at     TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS device_groups (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    name        TEXT NOT NULL UNIQUE,
    description TEXT,
    parent_id   INTEGER REFERENCES device_groups(id),
    created_at  TEXT NOT NULL DEFAULT (datetime('now'))
);

-- Insert default group
INSERT OR IGNORE INTO device_groups (name, description) VALUES ('default', 'Default device group');

-- Indexes
CREATE INDEX IF NOT EXISTS idx_devices_status ON devices(status);
CREATE INDEX IF NOT EXISTS idx_device_status_uid ON device_status(device_uid);
CREATE INDEX IF NOT EXISTS idx_status_history_device_time ON device_status_history(device_uid, reported_at);
CREATE INDEX IF NOT EXISTS idx_status_history_time ON device_status_history(reported_at);
