-- Extended metrics and agent state
-- Adds columns for uptime, user info, IPs, and network state storage

-- Add extended columns to metrics table
ALTER TABLE metrics ADD COLUMN IF NOT EXISTS uptime_seconds BIGINT;
ALTER TABLE metrics ADD COLUMN IF NOT EXISTS boot_time BIGINT;
ALTER TABLE metrics ADD COLUMN IF NOT EXISTS logged_in_user VARCHAR(255);
ALTER TABLE metrics ADD COLUMN IF NOT EXISTS user_idle_seconds BIGINT;
ALTER TABLE metrics ADD COLUMN IF NOT EXISTS public_ip VARCHAR(45);  -- Supports IPv6

-- Agent state table for current/latest agent information
-- This stores the latest snapshot of extended agent info (not time-series)
CREATE TABLE IF NOT EXISTS agent_state (
    agent_id UUID PRIMARY KEY REFERENCES agents(id) ON DELETE CASCADE,
    -- Network state
    network_interfaces JSONB,
    network_state_hash VARCHAR(32),
    -- Latest extended metrics (cached for quick access)
    uptime_seconds BIGINT,
    boot_time BIGINT,
    logged_in_user VARCHAR(255),
    user_idle_seconds BIGINT,
    public_ip VARCHAR(45),
    -- Timestamps
    network_updated_at TIMESTAMPTZ,
    metrics_updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Index for finding agents by public IP (useful for diagnostics)
CREATE INDEX IF NOT EXISTS idx_agent_state_public_ip ON agent_state(public_ip);

-- Add memory_total_bytes and disk_total_bytes to metrics for completeness
ALTER TABLE metrics ADD COLUMN IF NOT EXISTS memory_total_bytes BIGINT;
ALTER TABLE metrics ADD COLUMN IF NOT EXISTS disk_total_bytes BIGINT;
