-- SQLite dev mirror for remote access tables.

CREATE TABLE IF NOT EXISTS remote_access_devices (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    device_id TEXT NOT NULL UNIQUE,
    company_id INTEGER NOT NULL DEFAULT 1,
    whitelisted INTEGER NOT NULL DEFAULT 0,
    opt_in_mode TEXT NOT NULL DEFAULT 'none',
    last_random TEXT NULL,
    app_version TEXT NULL,
    last_seen_at TEXT NULL,
    notes TEXT NULL,
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS remote_access_sessions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    session_id TEXT NOT NULL UNIQUE,
    device_id TEXT NOT NULL,
    company_id INTEGER NOT NULL DEFAULT 1,
    operator_user_id INTEGER NULL,
    status TEXT NOT NULL DEFAULT 'pending',
    tunnel TEXT NOT NULL DEFAULT 'wireguard',
    endpoint TEXT NULL,
    wg_client_private_key TEXT NULL,
    wg_client_address TEXT NULL,
    wg_server_public_key TEXT NULL,
    wg_peer_allowed_ips TEXT NULL,
    expires_at INTEGER NULL,
    last_activity_at TEXT NULL,
    close_reason TEXT NULL,
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    closed_at TEXT NULL
);

CREATE TABLE IF NOT EXISTS remote_access_events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    session_id TEXT NULL,
    device_id TEXT NOT NULL,
    actor_user_id INTEGER NULL,
    action TEXT NOT NULL,
    reason TEXT NULL,
    meta_json TEXT NULL,
    client_ip TEXT NULL,
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_ra_evt_device ON remote_access_events(device_id, created_at);
CREATE INDEX IF NOT EXISTS idx_ra_sess_device ON remote_access_sessions(device_id, status);
