Explore the GuruRMM codebase to understand the current database schema and data models. Look at:

1. All migration files in server/migrations/ to understand current tables
2. Database models in server/src/db/ - especially agents.rs, clients.rs, sites.rs
3. How agents are currently associated with sites/clients

I need to understand the current data model so I can design a policy system that fits. Report back:
- Current table structure (agents, clients, sites, etc.)
- How agent-site-client relationships work
- Any existing configuration or settings patterns


I'll help you explore the GuruRMM codebase to understand the database schema and data models. Let me start by searching for the relevant files.


Bash

find "C:\Users\MikeSwanson\claude-projects\gururmm" -type f -name "*.rs" | grep -E "(db|model)" | head -20

Find database and model files in GuruRMM


Great! I found the migration files and database model files. Let me read them to understand the current schema:


     1→-- GuruRMM Initial Schema
     2→-- Creates tables for agents, metrics, commands, watchdog events, and users
     3→
     4→-- Enable UUID extension
     5→CREATE EXTENSION IF NOT EXISTS "pgcrypto";
     6→
     7→-- Agents table
     8→-- Stores registered agents and their current status
     9→CREATE TABLE agents (
    10→    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    11→    hostname VARCHAR(255) NOT NULL,
    12→    api_key_hash VARCHAR(255) NOT NULL,
    13→    os_type VARCHAR(50) NOT NULL,
    14→    os_version VARCHAR(100),
    15→    agent_version VARCHAR(50),
    16→    last_seen TIMESTAMPTZ,
    17→    status VARCHAR(20) DEFAULT 'offline',
    18→    created_at TIMESTAMPTZ DEFAULT NOW(),
    19→    updated_at TIMESTAMPTZ DEFAULT NOW()
    20→);
    21→
    22→-- Index for looking up agents by hostname
    23→CREATE INDEX idx_agents_hostname ON agents(hostname);
    24→
    25→-- Index for finding online agents
    26→CREATE INDEX idx_agents_status ON agents(status);
    27→
    28→-- Metrics table
    29→-- Time-series data for system metrics from agents
    30→CREATE TABLE metrics (
    31→    id BIGSERIAL PRIMARY KEY,
    32→    agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
    33→    timestamp TIMESTAMPTZ DEFAULT NOW(),
    34→    cpu_percent REAL,
    35→    memory_percent REAL,
    36→    memory_used_bytes BIGINT,
    37→    disk_percent REAL,
    38→    disk_used_bytes BIGINT,
    39→    network_rx_bytes BIGINT,
    40→    network_tx_bytes BIGINT
    41→);
    42→
    43→-- Index for querying metrics by agent and time
    44→CREATE INDEX idx_metrics_agent_time ON metrics(agent_id, timestamp DESC);
    45→
    46→-- Index for finding recent metrics
    47→CREATE INDEX idx_metrics_timestamp ON metrics(timestamp DESC);
    48→
    49→-- Users table
    50→-- Dashboard users for authentication
    51→CREATE TABLE users (
    52→    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    53→    email VARCHAR(255) UNIQUE NOT NULL,
    54→    password_hash VARCHAR(255),
    55→    name VARCHAR(255),
    56→    role VARCHAR(50) DEFAULT 'user',
    57→    sso_provider VARCHAR(50),
    58→    sso_id VARCHAR(255),
    59→    created_at TIMESTAMPTZ DEFAULT NOW(),
    60→    last_login TIMESTAMPTZ
    61→);
    62→
    63→-- Index for email lookups during login
    64→CREATE INDEX idx_users_email ON users(email);
    65→
    66→-- Index for SSO lookups
    67→CREATE INDEX idx_users_sso ON users(sso_provider, sso_id);
    68→
    69→-- Commands table
    70→-- Commands sent to agents and their results
    71→CREATE TABLE commands (
    72→    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    73→    agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
    74→    command_type VARCHAR(50) NOT NULL,
    75→    command_text TEXT NOT NULL,
    76→    status VARCHAR(20) DEFAULT 'pending',
    77→    exit_code INTEGER,
    78→    stdout TEXT,
    79→    stderr TEXT,
    80→    created_at TIMESTAMPTZ DEFAULT NOW(),
    81→    started_at TIMESTAMPTZ,
    82→    completed_at TIMESTAMPTZ,
    83→    created_by UUID REFERENCES users(id) ON DELETE SET NULL
    84→);
    85→
    86→-- Index for finding pending commands for an agent
    87→CREATE INDEX idx_commands_agent_status ON commands(agent_id, status);
    88→
    89→-- Index for command history queries
    90→CREATE INDEX idx_commands_created ON commands(created_at DESC);
    91→
    92→-- Watchdog events table
    93→-- Events from agent watchdog monitoring
    94→CREATE TABLE watchdog_events (
    95→    id BIGSERIAL PRIMARY KEY,
    96→    agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
    97→    timestamp TIMESTAMPTZ DEFAULT NOW(),
    98→    service_name VARCHAR(255) NOT NULL,
    99→    event_type VARCHAR(50) NOT NULL,
   100→    details TEXT
   101→);
   102→
   103→-- Index for querying events by agent and time
   104→CREATE INDEX idx_watchdog_agent_time ON watchdog_events(agent_id, timestamp DESC);
   105→
   106→-- Index for finding recent events
   107→CREATE INDEX idx_watchdog_timestamp ON watchdog_events(timestamp DESC);
   108→
   109→-- Function to update updated_at timestamp
   110→CREATE OR REPLACE FUNCTION update_updated_at_column()
   111→RETURNS TRIGGER AS $$
   112→BEGIN
   113→    NEW.updated_at = NOW();
   114→    RETURN NEW;
   115→END;
   116→$$ LANGUAGE plpgsql;
   117→
   118→-- Trigger for agents table
   119→CREATE TRIGGER update_agents_updated_at
   120→    BEFORE UPDATE ON agents
   121→    FOR EACH ROW
   122→    EXECUTE FUNCTION update_updated_at_column();
   123→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

-- GuruRMM Initial Schema
-- Creates tables for agents, metrics, commands, watchdog events, and users

-- Enable UUID extension
CREATE EXTENSION IF NOT EXISTS "pgcrypto";

-- Agents table
-- Stores registered agents and their current status
CREATE TABLE agents (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    hostname VARCHAR(255) NOT NULL,
    api_key_hash VARCHAR(255) NOT NULL,
    os_type VARCHAR(50) NOT NULL,
    os_version VARCHAR(100),
    agent_version VARCHAR(50),
    last_seen TIMESTAMPTZ,
    status VARCHAR(20) DEFAULT 'offline',
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Index for looking up agents by hostname
CREATE INDEX idx_agents_hostname ON agents(hostname);

-- Index for finding online agents
CREATE INDEX idx_agents_status ON agents(status);

-- Metrics table
-- Time-series data for system metrics from agents
CREATE TABLE metrics (
    id BIGSERIAL PRIMARY KEY,
    agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
    timestamp TIMESTAMPTZ DEFAULT NOW(),
    cpu_percent REAL,
    memory_percent REAL,
    memory_used_bytes BIGINT,
    disk_percent REAL,
    disk_used_bytes BIGINT,
    network_rx_bytes BIGINT,
    network_tx_bytes BIGINT
);

-- Index for querying metrics by agent and time
CREATE INDEX idx_metrics_agent_time ON metrics(agent_id, timestamp DESC);

-- Index for finding recent metrics
CREATE INDEX idx_metrics_timestamp ON metrics(timestamp DESC);

-- Users table
-- Dashboard users for authentication
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) UNIQUE NOT NULL,
    password_hash VARCHAR(255),
    name VARCHAR(255),
    role VARCHAR(50) DEFAULT 'user',
    sso_provider VARCHAR(50),
    sso_id VARCHAR(255),
    created_at TIMESTAMPTZ DEFAULT NOW(),
    last_login TIMESTAMPTZ
);

-- Index for email lookups during login
CREATE INDEX idx_users_email ON users(email);

-- Index for SSO lookups
CREATE INDEX idx_users_sso ON users(sso_provider, sso_id);

-- Commands table
-- Commands sent to agents and their results
CREATE TABLE commands (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
    command_type VARCHAR(50) NOT NULL,
    command_text TEXT NOT NULL,
    status VARCHAR(20) DEFAULT 'pending',
    exit_code INTEGER,
    stdout TEXT,
    stderr TEXT,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    started_at TIMESTAMPTZ,
    completed_at TIMESTAMPTZ,
    created_by UUID REFERENCES users(id) ON DELETE SET NULL
);

-- Index for finding pending commands for an agent
CREATE INDEX idx_commands_agent_status ON commands(agent_id, status);

-- Index for command history queries
CREATE INDEX idx_commands_created ON commands(created_at DESC);

-- Watchdog events table
-- Events from agent watchdog monitoring
CREATE TABLE watchdog_events (
    id BIGSERIAL PRIMARY KEY,
    agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
    timestamp TIMESTAMPTZ DEFAULT NOW(),
    service_name VARCHAR(255) NOT NULL,
    event_type VARCHAR(50) NOT NULL,
    details TEXT
);

-- Index for querying events by agent and time
CREATE INDEX idx_watchdog_agent_time ON watchdog_events(agent_id, timestamp DESC);

-- Index for finding recent events
CREATE INDEX idx_watchdog_timestamp ON watchdog_events(timestamp DESC);

-- Function to update updated_at timestamp
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Trigger for agents table
CREATE TRIGGER update_agents_updated_at
    BEFORE UPDATE ON agents
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();


     1→-- GuruRMM Clients and Sites Schema
     2→-- Adds multi-tenant support with clients, sites, and site-based agent registration
     3→
     4→-- Clients table (organizations/companies)
     5→CREATE TABLE clients (
     6→    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
     7→    name VARCHAR(255) NOT NULL,
     8→    code VARCHAR(50) UNIQUE, -- Optional short code like "ACME"
     9→    notes TEXT,
    10→    is_active BOOLEAN DEFAULT TRUE,
    11→    created_at TIMESTAMPTZ DEFAULT NOW(),
    12→    updated_at TIMESTAMPTZ DEFAULT NOW()
    13→);
    14→
    15→CREATE INDEX idx_clients_name ON clients(name);
    16→CREATE INDEX idx_clients_code ON clients(code);
    17→
    18→-- Trigger for clients updated_at
    19→CREATE TRIGGER update_clients_updated_at
    20→    BEFORE UPDATE ON clients
    21→    FOR EACH ROW
    22→    EXECUTE FUNCTION update_updated_at_column();
    23→
    24→-- Sites table (locations under a client)
    25→CREATE TABLE sites (
    26→    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    27→    client_id UUID NOT NULL REFERENCES clients(id) ON DELETE CASCADE,
    28→    name VARCHAR(255) NOT NULL,
    29→    -- Site code: human-friendly, used for agent registration (e.g., "BLUE-TIGER-4829")
    30→    site_code VARCHAR(50) UNIQUE NOT NULL,
    31→    -- API key hash for this site (all agents at site share this key)
    32→    api_key_hash VARCHAR(255) NOT NULL,
    33→    address TEXT,
    34→    notes TEXT,
    35→    is_active BOOLEAN DEFAULT TRUE,
    36→    created_at TIMESTAMPTZ DEFAULT NOW(),
    37→    updated_at TIMESTAMPTZ DEFAULT NOW()
    38→);
    39→
    40→CREATE INDEX idx_sites_client ON sites(client_id);
    41→CREATE INDEX idx_sites_code ON sites(site_code);
    42→CREATE INDEX idx_sites_api_key ON sites(api_key_hash);
    43→
    44→-- Trigger for sites updated_at
    45→CREATE TRIGGER update_sites_updated_at
    46→    BEFORE UPDATE ON sites
    47→    FOR EACH ROW
    48→    EXECUTE FUNCTION update_updated_at_column();
    49→
    50→-- Add new columns to agents table
    51→-- device_id: unique hardware-derived identifier for the machine
    52→ALTER TABLE agents ADD COLUMN device_id VARCHAR(255);
    53→
    54→-- site_id: which site this agent belongs to (nullable for legacy agents)
    55→ALTER TABLE agents ADD COLUMN site_id UUID REFERENCES sites(id) ON DELETE SET NULL;
    56→
    57→-- Make api_key_hash nullable (new agents will use site's api_key)
    58→ALTER TABLE agents ALTER COLUMN api_key_hash DROP NOT NULL;
    59→
    60→-- Index for looking up agents by device_id within a site
    61→CREATE UNIQUE INDEX idx_agents_site_device ON agents(site_id, device_id) WHERE site_id IS NOT NULL AND device_id IS NOT NULL;
    62→
    63→-- Index for site lookups
    64→CREATE INDEX idx_agents_site ON agents(site_id);
    65→
    66→-- Registration tokens table (optional: for secure site code distribution)
    67→CREATE TABLE registration_tokens (
    68→    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    69→    site_id UUID NOT NULL REFERENCES sites(id) ON DELETE CASCADE,
    70→    token_hash VARCHAR(255) NOT NULL,
    71→    description VARCHAR(255),
    72→    uses_remaining INTEGER, -- NULL = unlimited
    73→    expires_at TIMESTAMPTZ,
    74→    created_at TIMESTAMPTZ DEFAULT NOW(),
    75→    created_by UUID REFERENCES users(id) ON DELETE SET NULL
    76→);
    77→
    78→CREATE INDEX idx_reg_tokens_site ON registration_tokens(site_id);
    79→CREATE INDEX idx_reg_tokens_hash ON registration_tokens(token_hash);
    80→
    81→-- Function to generate a random site code (WORD-WORD-####)
    82→-- This is just a helper; actual generation should be in application code
    83→-- for better word lists
    84→CREATE OR REPLACE FUNCTION generate_site_code() RETURNS VARCHAR(50) AS $$
    85→DECLARE
    86→    words TEXT[] := ARRAY['ALPHA', 'BETA', 'GAMMA', 'DELTA', 'ECHO', 'FOXTROT',
    87→                          'BLUE', 'GREEN', 'RED', 'GOLD', 'SILVER', 'IRON',
    88→                          'HAWK', 'EAGLE', 'TIGER', 'LION', 'WOLF', 'BEAR',
    89→                          'NORTH', 'SOUTH', 'EAST', 'WEST', 'PEAK', 'VALLEY',
    90→                          'RIVER', 'OCEAN', 'STORM', 'CLOUD', 'STAR', 'MOON'];
    91→    word1 TEXT;
    92→    word2 TEXT;
    93→    num INTEGER;
    94→BEGIN
    95→    word1 := words[1 + floor(random() * array_length(words, 1))::int];
    96→    word2 := words[1 + floor(random() * array_length(words, 1))::int];
    97→    num := 1000 + floor(random() * 9000)::int;
    98→    RETURN word1 || '-' || word2 || '-' || num::text;
    99→END;
   100→$$ LANGUAGE plpgsql;
   101→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

-- GuruRMM Clients and Sites Schema
-- Adds multi-tenant support with clients, sites, and site-based agent registration

-- Clients table (organizations/companies)
CREATE TABLE clients (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL,
    code VARCHAR(50) UNIQUE, -- Optional short code like "ACME"
    notes TEXT,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_clients_name ON clients(name);
CREATE INDEX idx_clients_code ON clients(code);

-- Trigger for clients updated_at
CREATE TRIGGER update_clients_updated_at
    BEFORE UPDATE ON clients
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();

-- Sites table (locations under a client)
CREATE TABLE sites (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    client_id UUID NOT NULL REFERENCES clients(id) ON DELETE CASCADE,
    name VARCHAR(255) NOT NULL,
    -- Site code: human-friendly, used for agent registration (e.g., "BLUE-TIGER-4829")
    site_code VARCHAR(50) UNIQUE NOT NULL,
    -- API key hash for this site (all agents at site share this key)
    api_key_hash VARCHAR(255) NOT NULL,
    address TEXT,
    notes TEXT,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_sites_client ON sites(client_id);
CREATE INDEX idx_sites_code ON sites(site_code);
CREATE INDEX idx_sites_api_key ON sites(api_key_hash);

-- Trigger for sites updated_at
CREATE TRIGGER update_sites_updated_at
    BEFORE UPDATE ON sites
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();

-- Add new columns to agents table
-- device_id: unique hardware-derived identifier for the machine
ALTER TABLE agents ADD COLUMN device_id VARCHAR(255);

-- site_id: which site this agent belongs to (nullable for legacy agents)
ALTER TABLE agents ADD COLUMN site_id UUID REFERENCES sites(id) ON DELETE SET NULL;

-- Make api_key_hash nullable (new agents will use site's api_key)
ALTER TABLE agents ALTER COLUMN api_key_hash DROP NOT NULL;

-- Index for looking up agents by device_id within a site
CREATE UNIQUE INDEX idx_agents_site_device ON agents(site_id, device_id) WHERE site_id IS NOT NULL AND device_id IS NOT NULL;

-- Index for site lookups
CREATE INDEX idx_agents_site ON agents(site_id);

-- Registration tokens table (optional: for secure site code distribution)
CREATE TABLE registration_tokens (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    site_id UUID NOT NULL REFERENCES sites(id) ON DELETE CASCADE,
    token_hash VARCHAR(255) NOT NULL,
    description VARCHAR(255),
    uses_remaining INTEGER, -- NULL = unlimited
    expires_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    created_by UUID REFERENCES users(id) ON DELETE SET NULL
);

CREATE INDEX idx_reg_tokens_site ON registration_tokens(site_id);
CREATE INDEX idx_reg_tokens_hash ON registration_tokens(token_hash);

-- Function to generate a random site code (WORD-WORD-####)
-- This is just a helper; actual generation should be in application code
-- for better word lists
CREATE OR REPLACE FUNCTION generate_site_code() RETURNS VARCHAR(50) AS $$
DECLARE
    words TEXT[] := ARRAY['ALPHA', 'BETA', 'GAMMA', 'DELTA', 'ECHO', 'FOXTROT',
                          'BLUE', 'GREEN', 'RED', 'GOLD', 'SILVER', 'IRON',
                          'HAWK', 'EAGLE', 'TIGER', 'LION', 'WOLF', 'BEAR',
                          'NORTH', 'SOUTH', 'EAST', 'WEST', 'PEAK', 'VALLEY',
                          'RIVER', 'OCEAN', 'STORM', 'CLOUD', 'STAR', 'MOON'];
    word1 TEXT;
    word2 TEXT;
    num INTEGER;
BEGIN
    word1 := words[1 + floor(random() * array_length(words, 1))::int];
    word2 := words[1 + floor(random() * array_length(words, 1))::int];
    num := 1000 + floor(random() * 9000)::int;
    RETURN word1 || '-' || word2 || '-' || num::text;
END;
$$ LANGUAGE plpgsql;


     1→-- Extended metrics and agent state
     2→-- Adds columns for uptime, user info, IPs, and network state storage
     3→
     4→-- Add extended columns to metrics table
     5→ALTER TABLE metrics ADD COLUMN IF NOT EXISTS uptime_seconds BIGINT;
     6→ALTER TABLE metrics ADD COLUMN IF NOT EXISTS boot_time BIGINT;
     7→ALTER TABLE metrics ADD COLUMN IF NOT EXISTS logged_in_user VARCHAR(255);
     8→ALTER TABLE metrics ADD COLUMN IF NOT EXISTS user_idle_seconds BIGINT;
     9→ALTER TABLE metrics ADD COLUMN IF NOT EXISTS public_ip VARCHAR(45);  -- Supports IPv6
    10→
    11→-- Agent state table for current/latest agent information
    12→-- This stores the latest snapshot of extended agent info (not time-series)
    13→CREATE TABLE IF NOT EXISTS agent_state (
    14→    agent_id UUID PRIMARY KEY REFERENCES agents(id) ON DELETE CASCADE,
    15→    -- Network state
    16→    network_interfaces JSONB,
    17→    network_state_hash VARCHAR(32),
    18→    -- Latest extended metrics (cached for quick access)
    19→    uptime_seconds BIGINT,
    20→    boot_time BIGINT,
    21→    logged_in_user VARCHAR(255),
    22→    user_idle_seconds BIGINT,
    23→    public_ip VARCHAR(45),
    24→    -- Timestamps
    25→    network_updated_at TIMESTAMPTZ,
    26→    metrics_updated_at TIMESTAMPTZ DEFAULT NOW()
    27→);
    28→
    29→-- Index for finding agents by public IP (useful for diagnostics)
    30→CREATE INDEX IF NOT EXISTS idx_agent_state_public_ip ON agent_state(public_ip);
    31→
    32→-- Add memory_total_bytes and disk_total_bytes to metrics for completeness
    33→ALTER TABLE metrics ADD COLUMN IF NOT EXISTS memory_total_bytes BIGINT;
    34→ALTER TABLE metrics ADD COLUMN IF NOT EXISTS disk_total_bytes BIGINT;
    35→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

-- 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;


     1→//! Agent database operations
     2→
     3→use chrono::{DateTime, Utc};
     4→use serde::{Deserialize, Serialize};
     5→use sqlx::PgPool;
     6→use uuid::Uuid;
     7→
     8→/// Agent record from database
     9→#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
    10→pub struct Agent {
    11→    pub id: Uuid,
    12→    pub hostname: String,
    13→    #[serde(skip_serializing)]
    14→    pub api_key_hash: Option<String>,  // Nullable: new agents use site's api_key
    15→    pub os_type: String,
    16→    pub os_version: Option<String>,
    17→    pub agent_version: Option<String>,
    18→    pub last_seen: Option<DateTime<Utc>>,
    19→    pub status: String,
    20→    pub created_at: DateTime<Utc>,
    21→    pub updated_at: DateTime<Utc>,
    22→    // New fields for site-based registration
    23→    pub device_id: Option<String>,     // Hardware-derived unique ID
    24→    pub site_id: Option<Uuid>,         // Which site this agent belongs to
    25→}
    26→
    27→/// Agent without sensitive fields (for API responses)
    28→#[derive(Debug, Clone, Serialize, Deserialize)]
    29→pub struct AgentResponse {
    30→    pub id: Uuid,
    31→    pub hostname: String,
    32→    pub os_type: String,
    33→    pub os_version: Option<String>,
    34→    pub agent_version: Option<String>,
    35→    pub last_seen: Option<DateTime<Utc>>,
    36→    pub status: String,
    37→    pub created_at: DateTime<Utc>,
    38→    pub device_id: Option<String>,
    39→    pub site_id: Option<Uuid>,
    40→    pub site_name: Option<String>,
    41→    pub client_name: Option<String>,
    42→}
    43→
    44→impl From<Agent> for AgentResponse {
    45→    fn from(agent: Agent) -> Self {
    46→        Self {
    47→            id: agent.id,
    48→            hostname: agent.hostname,
    49→            os_type: agent.os_type,
    50→            os_version: agent.os_version,
    51→            agent_version: agent.agent_version,
    52→            last_seen: agent.last_seen,
    53→            status: agent.status,
    54→            created_at: agent.created_at,
    55→            device_id: agent.device_id,
    56→            site_id: agent.site_id,
    57→            site_name: None,
    58→            client_name: None,
    59→        }
    60→    }
    61→}
    62→
    63→/// Create a new agent registration
    64→#[derive(Debug, Clone, Deserialize)]
    65→pub struct CreateAgent {
    66→    pub hostname: String,
    67→    pub api_key_hash: String,
    68→    pub os_type: String,
    69→    pub os_version: Option<String>,
    70→    pub agent_version: Option<String>,
    71→}
    72→
    73→/// Insert a new agent into the database
    74→pub async fn create_agent(pool: &PgPool, agent: CreateAgent) -> Result<Agent, sqlx::Error> {
    75→    sqlx::query_as::<_, Agent>(
    76→        r#"
    77→        INSERT INTO agents (hostname, api_key_hash, os_type, os_version, agent_version, status)
    78→        VALUES ($1, $2, $3, $4, $5, 'offline')
    79→        RETURNING *
    80→        "#,
    81→    )
    82→    .bind(&agent.hostname)
    83→    .bind(&agent.api_key_hash)
    84→    .bind(&agent.os_type)
    85→    .bind(&agent.os_version)
    86→    .bind(&agent.agent_version)
    87→    .fetch_one(pool)
    88→    .await
    89→}
    90→
    91→/// Get an agent by ID
    92→pub async fn get_agent_by_id(pool: &PgPool, id: Uuid) -> Result<Option<Agent>, sqlx::Error> {
    93→    sqlx::query_as::<_, Agent>("SELECT * FROM agents WHERE id = $1")
    94→        .bind(id)
    95→        .fetch_optional(pool)
    96→        .await
    97→}
    98→
    99→/// Get an agent by API key hash
   100→pub async fn get_agent_by_api_key_hash(
   101→    pool: &PgPool,
   102→    api_key_hash: &str,
   103→) -> Result<Option<Agent>, sqlx::Error> {
   104→    sqlx::query_as::<_, Agent>("SELECT * FROM agents WHERE api_key_hash = $1")
   105→        .bind(api_key_hash)
   106→        .fetch_optional(pool)
   107→        .await
   108→}
   109→
   110→/// Get all agents
   111→pub async fn get_all_agents(pool: &PgPool) -> Result<Vec<Agent>, sqlx::Error> {
   112→    sqlx::query_as::<_, Agent>("SELECT * FROM agents ORDER BY hostname")
   113→        .fetch_all(pool)
   114→        .await
   115→}
   116→
   117→/// Get agents by status
   118→pub async fn get_agents_by_status(
   119→    pool: &PgPool,
   120→    status: &str,
   121→) -> Result<Vec<Agent>, sqlx::Error> {
   122→    sqlx::query_as::<_, Agent>("SELECT * FROM agents WHERE status = $1 ORDER BY hostname")
   123→        .bind(status)
   124→        .fetch_all(pool)
   125→        .await
   126→}
   127→
   128→/// Update agent status and last_seen
   129→pub async fn update_agent_status(
   130→    pool: &PgPool,
   131→    id: Uuid,
   132→    status: &str,
   133→) -> Result<(), sqlx::Error> {
   134→    sqlx::query("UPDATE agents SET status = $1, last_seen = NOW() WHERE id = $2")
   135→        .bind(status)
   136→        .bind(id)
   137→        .execute(pool)
   138→        .await?;
   139→    Ok(())
   140→}
   141→
   142→/// Update agent info (on connection)
   143→pub async fn update_agent_info(
   144→    pool: &PgPool,
   145→    id: Uuid,
   146→    hostname: Option<&str>,
   147→    os_version: Option<&str>,
   148→    agent_version: Option<&str>,
   149→) -> Result<(), sqlx::Error> {
   150→    sqlx::query(
   151→        r#"
   152→        UPDATE agents
   153→        SET hostname = COALESCE($1, hostname),
   154→            os_version = COALESCE($2, os_version),
   155→            agent_version = COALESCE($3, agent_version),
   156→            last_seen = NOW(),
   157→            status = 'online'
   158→        WHERE id = $4
   159→        "#,
   160→    )
   161→    .bind(hostname)
   162→    .bind(os_version)
   163→    .bind(agent_version)
   164→    .bind(id)
   165→    .execute(pool)
   166→    .await?;
   167→    Ok(())
   168→}
   169→
   170→/// Delete an agent
   171→pub async fn delete_agent(pool: &PgPool, id: Uuid) -> Result<bool, sqlx::Error> {
   172→    let result = sqlx::query("DELETE FROM agents WHERE id = $1")
   173→        .bind(id)
   174→        .execute(pool)
   175→        .await?;
   176→    Ok(result.rows_affected() > 0)
   177→}
   178→
   179→/// Get agent count statistics
   180→#[derive(Debug, Clone, Serialize, Deserialize)]
   181→pub struct AgentStats {
   182→    pub total: i64,
   183→    pub online: i64,
   184→    pub offline: i64,
   185→}
   186→
   187→pub async fn get_agent_stats(pool: &PgPool) -> Result<AgentStats, sqlx::Error> {
   188→    let total: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM agents")
   189→        .fetch_one(pool)
   190→        .await?;
   191→
   192→    let online: (i64,) =
   193→        sqlx::query_as("SELECT COUNT(*) FROM agents WHERE status = 'online'")
   194→            .fetch_one(pool)
   195→            .await?;
   196→
   197→    Ok(AgentStats {
   198→        total: total.0,
   199→        online: online.0,
   200→        offline: total.0 - online.0,
   201→    })
   202→}
   203→
   204→// ============================================================================
   205→// Site-based agent operations
   206→// ============================================================================
   207→
   208→/// Data for creating an agent via site registration
   209→#[derive(Debug, Clone)]
   210→pub struct CreateAgentWithSite {
   211→    pub site_id: Uuid,
   212→    pub device_id: String,
   213→    pub hostname: String,
   214→    pub os_type: String,
   215→    pub os_version: Option<String>,
   216→    pub agent_version: Option<String>,
   217→}
   218→
   219→/// Create a new agent under a site (site-based registration)
   220→pub async fn create_agent_with_site(
   221→    pool: &PgPool,
   222→    agent: CreateAgentWithSite,
   223→) -> Result<Agent, sqlx::Error> {
   224→    sqlx::query_as::<_, Agent>(
   225→        r#"
   226→        INSERT INTO agents (site_id, device_id, hostname, os_type, os_version, agent_version, status)
   227→        VALUES ($1, $2, $3, $4, $5, $6, 'offline')
   228→        RETURNING *
   229→        "#,
   230→    )
   231→    .bind(&agent.site_id)
   232→    .bind(&agent.device_id)
   233→    .bind(&agent.hostname)
   234→    .bind(&agent.os_type)
   235→    .bind(&agent.os_version)
   236→    .bind(&agent.agent_version)
   237→    .fetch_one(pool)
   238→    .await
   239→}
   240→
   241→/// Get an agent by site_id and device_id (for site-based auth)
   242→pub async fn get_agent_by_site_and_device(
   243→    pool: &PgPool,
   244→    site_id: Uuid,
   245→    device_id: &str,
   246→) -> Result<Option<Agent>, sqlx::Error> {
   247→    sqlx::query_as::<_, Agent>(
   248→        "SELECT * FROM agents WHERE site_id = $1 AND device_id = $2"
   249→    )
   250→    .bind(site_id)
   251→    .bind(device_id)
   252→    .fetch_optional(pool)
   253→    .await
   254→}
   255→
   256→/// Get all agents for a site
   257→pub async fn get_agents_by_site(pool: &PgPool, site_id: Uuid) -> Result<Vec<Agent>, sqlx::Error> {
   258→    sqlx::query_as::<_, Agent>(
   259→        "SELECT * FROM agents WHERE site_id = $1 ORDER BY hostname"
   260→    )
   261→    .bind(site_id)
   262→    .fetch_all(pool)
   263→    .await
   264→}
   265→
   266→/// Agent with site and client details for API responses
   267→#[derive(Debug, Clone, sqlx::FromRow, Serialize)]
   268→pub struct AgentWithDetails {
   269→    pub id: Uuid,
   270→    pub hostname: String,
   271→    pub os_type: String,
   272→    pub os_version: Option<String>,
   273→    pub agent_version: Option<String>,
   274→    pub last_seen: Option<DateTime<Utc>>,
   275→    pub status: String,
   276→    pub created_at: DateTime<Utc>,
   277→    pub device_id: Option<String>,
   278→    pub site_id: Option<Uuid>,
   279→    pub site_name: Option<String>,
   280→    pub client_id: Option<Uuid>,
   281→    pub client_name: Option<String>,
   282→}
   283→
   284→/// Get all agents with site/client details
   285→pub async fn get_all_agents_with_details(pool: &PgPool) -> Result<Vec<AgentWithDetails>, sqlx::Error> {
   286→    sqlx::query_as::<_, AgentWithDetails>(
   287→        r#"
   288→        SELECT
   289→            a.id, a.hostname, a.os_type, a.os_version, a.agent_version,
   290→            a.last_seen, a.status, a.created_at, a.device_id, a.site_id,
   291→            s.name as site_name,
   292→            c.id as client_id,
   293→            c.name as client_name
   294→        FROM agents a
   295→        LEFT JOIN sites s ON a.site_id = s.id
   296→        LEFT JOIN clients c ON s.client_id = c.id
   297→        ORDER BY c.name, s.name, a.hostname
   298→        "#,
   299→    )
   300→    .fetch_all(pool)
   301→    .await
   302→}
   303→
   304→/// Update agent info including device_id (on connection)
   305→pub async fn update_agent_info_full(
   306→    pool: &PgPool,
   307→    id: Uuid,
   308→    hostname: Option<&str>,
   309→    device_id: Option<&str>,
   310→    os_version: Option<&str>,
   311→    agent_version: Option<&str>,
   312→) -> Result<(), sqlx::Error> {
   313→    sqlx::query(
   314→        r#"
   315→        UPDATE agents
   316→        SET hostname = COALESCE($1, hostname),
   317→            device_id = COALESCE($2, device_id),
   318→            os_version = COALESCE($3, os_version),
   319→            agent_version = COALESCE($4, agent_version),
   320→            last_seen = NOW(),
   321→            status = 'online'
   322→        WHERE id = $5
   323→        "#,
   324→    )
   325→    .bind(hostname)
   326→    .bind(device_id)
   327→    .bind(os_version)
   328→    .bind(agent_version)
   329→    .bind(id)
   330→    .execute(pool)
   331→    .await?;
   332→    Ok(())
   333→}
   334→
   335→/// Move an agent to a different site (or remove from site if site_id is None)
   336→pub async fn move_agent_to_site(
   337→    pool: &PgPool,
   338→    agent_id: Uuid,
   339→    site_id: Option<Uuid>,
   340→) -> Result<Option<Agent>, sqlx::Error> {
   341→    sqlx::query_as::<_, Agent>(
   342→        r#"
   343→        UPDATE agents
   344→        SET site_id = $1,
   345→            updated_at = NOW()
   346→        WHERE id = $2
   347→        RETURNING *
   348→        "#,
   349→    )
   350→    .bind(site_id)
   351→    .bind(agent_id)
   352→    .fetch_optional(pool)
   353→    .await
   354→}
   355→
   356→/// Get agents that are not assigned to any site
   357→pub async fn get_unassigned_agents(pool: &PgPool) -> Result<Vec<Agent>, sqlx::Error> {
   358→    sqlx::query_as::<_, Agent>(
   359→        "SELECT * FROM agents WHERE site_id IS NULL ORDER BY hostname"
   360→    )
   361→    .fetch_all(pool)
   362→    .await
   363→}
   364→
   365→/// Update agent last_seen timestamp (for heartbeat)
   366→pub async fn update_agent_last_seen(
   367→    pool: &PgPool,
   368→    id: Uuid,
   369→) -> Result<(), sqlx::Error> {
   370→    sqlx::query("UPDATE agents SET last_seen = NOW(), status = 'online' WHERE id = $1")
   371→        .bind(id)
   372→        .execute(pool)
   373→        .await?;
   374→    Ok(())
   375→}
   376→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

//! Agent database operations

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use uuid::Uuid;

/// Agent record from database
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct Agent {
    pub id: Uuid,
    pub hostname: String,
    #[serde(skip_serializing)]
    pub api_key_hash: Option<String>,  // Nullable: new agents use site's api_key
    pub os_type: String,
    pub os_version: Option<String>,
    pub agent_version: Option<String>,
    pub last_seen: Option<DateTime<Utc>>,
    pub status: String,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    // New fields for site-based registration
    pub device_id: Option<String>,     // Hardware-derived unique ID
    pub site_id: Option<Uuid>,         // Which site this agent belongs to
}

/// Agent without sensitive fields (for API responses)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentResponse {
    pub id: Uuid,
    pub hostname: String,
    pub os_type: String,
    pub os_version: Option<String>,
    pub agent_version: Option<String>,
    pub last_seen: Option<DateTime<Utc>>,
    pub status: String,
    pub created_at: DateTime<Utc>,
    pub device_id: Option<String>,
    pub site_id: Option<Uuid>,
    pub site_name: Option<String>,
    pub client_name: Option<String>,
}

impl From<Agent> for AgentResponse {
    fn from(agent: Agent) -> Self {
        Self {
            id: agent.id,
            hostname: agent.hostname,
            os_type: agent.os_type,
            os_version: agent.os_version,
            agent_version: agent.agent_version,
            last_seen: agent.last_seen,
            status: agent.status,
            created_at: agent.created_at,
            device_id: agent.device_id,
            site_id: agent.site_id,
            site_name: None,
            client_name: None,
        }
    }
}

/// Create a new agent registration
#[derive(Debug, Clone, Deserialize)]
pub struct CreateAgent {
    pub hostname: String,
    pub api_key_hash: String,
    pub os_type: String,
    pub os_version: Option<String>,
    pub agent_version: Option<String>,
}

/// Insert a new agent into the database
pub async fn create_agent(pool: &PgPool, agent: CreateAgent) -> Result<Agent, sqlx::Error> {
    sqlx::query_as::<_, Agent>(
        r#"
        INSERT INTO agents (hostname, api_key_hash, os_type, os_version, agent_version, status)
        VALUES ($1, $2, $3, $4, $5, 'offline')
        RETURNING *
        "#,
    )
    .bind(&agent.hostname)
    .bind(&agent.api_key_hash)
    .bind(&agent.os_type)
    .bind(&agent.os_version)
    .bind(&agent.agent_version)
    .fetch_one(pool)
    .await
}

/// Get an agent by ID
pub async fn get_agent_by_id(pool: &PgPool, id: Uuid) -> Result<Option<Agent>, sqlx::Error> {
    sqlx::query_as::<_, Agent>("SELECT * FROM agents WHERE id = $1")
        .bind(id)
        .fetch_optional(pool)
        .await
}

/// Get an agent by API key hash
pub async fn get_agent_by_api_key_hash(
    pool: &PgPool,
    api_key_hash: &str,
) -> Result<Option<Agent>, sqlx::Error> {
    sqlx::query_as::<_, Agent>("SELECT * FROM agents WHERE api_key_hash = $1")
        .bind(api_key_hash)
        .fetch_optional(pool)
        .await
}

/// Get all agents
pub async fn get_all_agents(pool: &PgPool) -> Result<Vec<Agent>, sqlx::Error> {
    sqlx::query_as::<_, Agent>("SELECT * FROM agents ORDER BY hostname")
        .fetch_all(pool)
        .await
}

/// Get agents by status
pub async fn get_agents_by_status(
    pool: &PgPool,
    status: &str,
) -> Result<Vec<Agent>, sqlx::Error> {
    sqlx::query_as::<_, Agent>("SELECT * FROM agents WHERE status = $1 ORDER BY hostname")
        .bind(status)
        .fetch_all(pool)
        .await
}

/// Update agent status and last_seen
pub async fn update_agent_status(
    pool: &PgPool,
    id: Uuid,
    status: &str,
) -> Result<(), sqlx::Error> {
    sqlx::query("UPDATE agents SET status = $1, last_seen = NOW() WHERE id = $2")
        .bind(status)
        .bind(id)
        .execute(pool)
        .await?;
    Ok(())
}

/// Update agent info (on connection)
pub async fn update_agent_info(
    pool: &PgPool,
    id: Uuid,
    hostname: Option<&str>,
    os_version: Option<&str>,
    agent_version: Option<&str>,
) -> Result<(), sqlx::Error> {
    sqlx::query(
        r#"
        UPDATE agents
        SET hostname = COALESCE($1, hostname),
            os_version = COALESCE($2, os_version),
            agent_version = COALESCE($3, agent_version),
            last_seen = NOW(),
            status = 'online'
        WHERE id = $4
        "#,
    )
    .bind(hostname)
    .bind(os_version)
    .bind(agent_version)
    .bind(id)
    .execute(pool)
    .await?;
    Ok(())
}

/// Delete an agent
pub async fn delete_agent(pool: &PgPool, id: Uuid) -> Result<bool, sqlx::Error> {
    let result = sqlx::query("DELETE FROM agents WHERE id = $1")
        .bind(id)
        .execute(pool)
        .await?;
    Ok(result.rows_affected() > 0)
}

/// Get agent count statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentStats {
    pub total: i64,
    pub online: i64,
    pub offline: i64,
}

pub async fn get_agent_stats(pool: &PgPool) -> Result<AgentStats, sqlx::Error> {
    let total: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM agents")
        .fetch_one(pool)
        .await?;

    let online: (i64,) =
        sqlx::query_as("SELECT COUNT(*) FROM agents WHERE status = 'online'")
            .fetch_one(pool)
            .await?;

    Ok(AgentStats {
        total: total.0,
        online: online.0,
        offline: total.0 - online.0,
    })
}

// ============================================================================
// Site-based agent operations
// ============================================================================

/// Data for creating an agent via site registration
#[derive(Debug, Clone)]
pub struct CreateAgentWithSite {
    pub site_id: Uuid,
    pub device_id: String,
    pub hostname: String,
    pub os_type: String,
    pub os_version: Option<String>,
    pub agent_version: Option<String>,
}

/// Create a new agent under a site (site-based registration)
pub async fn create_agent_with_site(
    pool: &PgPool,
    agent: CreateAgentWithSite,
) -> Result<Agent, sqlx::Error> {
    sqlx::query_as::<_, Agent>(
        r#"
        INSERT INTO agents (site_id, device_id, hostname, os_type, os_version, agent_version, status)
        VALUES ($1, $2, $3, $4, $5, $6, 'offline')
        RETURNING *
        "#,
    )
    .bind(&agent.site_id)
    .bind(&agent.device_id)
    .bind(&agent.hostname)
    .bind(&agent.os_type)
    .bind(&agent.os_version)
    .bind(&agent.agent_version)
    .fetch_one(pool)
    .await
}

/// Get an agent by site_id and device_id (for site-based auth)
pub async fn get_agent_by_site_and_device(
    pool: &PgPool,
    site_id: Uuid,
    device_id: &str,
) -> Result<Option<Agent>, sqlx::Error> {
    sqlx::query_as::<_, Agent>(
        "SELECT * FROM agents WHERE site_id = $1 AND device_id = $2"
    )
    .bind(site_id)
    .bind(device_id)
    .fetch_optional(pool)
    .await
}

/// Get all agents for a site
pub async fn get_agents_by_site(pool: &PgPool, site_id: Uuid) -> Result<Vec<Agent>, sqlx::Error> {
    sqlx::query_as::<_, Agent>(
        "SELECT * FROM agents WHERE site_id = $1 ORDER BY hostname"
    )
    .bind(site_id)
    .fetch_all(pool)
    .await
}

/// Agent with site and client details for API responses
#[derive(Debug, Clone, sqlx::FromRow, Serialize)]
pub struct AgentWithDetails {
    pub id: Uuid,
    pub hostname: String,
    pub os_type: String,
    pub os_version: Option<String>,
    pub agent_version: Option<String>,
    pub last_seen: Option<DateTime<Utc>>,
    pub status: String,
    pub created_at: DateTime<Utc>,
    pub device_id: Option<String>,
    pub site_id: Option<Uuid>,
    pub site_name: Option<String>,
    pub client_id: Option<Uuid>,
    pub client_name: Option<String>,
}

/// Get all agents with site/client details
pub async fn get_all_agents_with_details(pool: &PgPool) -> Result<Vec<AgentWithDetails>, sqlx::Error> {
    sqlx::query_as::<_, AgentWithDetails>(
        r#"
        SELECT
            a.id, a.hostname, a.os_type, a.os_version, a.agent_version,
            a.last_seen, a.status, a.created_at, a.device_id, a.site_id,
            s.name as site_name,
            c.id as client_id,
            c.name as client_name
        FROM agents a
        LEFT JOIN sites s ON a.site_id = s.id
        LEFT JOIN clients c ON s.client_id = c.id
        ORDER BY c.name, s.name, a.hostname
        "#,
    )
    .fetch_all(pool)
    .await
}

/// Update agent info including device_id (on connection)
pub async fn update_agent_info_full(
    pool: &PgPool,
    id: Uuid,
    hostname: Option<&str>,
    device_id: Option<&str>,
    os_version: Option<&str>,
    agent_version: Option<&str>,
) -> Result<(), sqlx::Error> {
    sqlx::query(
        r#"
        UPDATE agents
        SET hostname = COALESCE($1, hostname),
            device_id = COALESCE($2, device_id),
            os_version = COALESCE($3, os_version),
            agent_version = COALESCE($4, agent_version),
            last_seen = NOW(),
            status = 'online'
        WHERE id = $5
        "#,
    )
    .bind(hostname)
    .bind(device_id)
    .bind(os_version)
    .bind(agent_version)
    .bind(id)
    .execute(pool)
    .await?;
    Ok(())
}

/// Move an agent to a different site (or remove from site if site_id is None)
pub async fn move_agent_to_site(
    pool: &PgPool,
    agent_id: Uuid,
    site_id: Option<Uuid>,
) -> Result<Option<Agent>, sqlx::Error> {
    sqlx::query_as::<_, Agent>(
        r#"
        UPDATE agents
        SET site_id = $1,
            updated_at = NOW()
        WHERE id = $2
        RETURNING *
        "#,
    )
    .bind(site_id)
    .bind(agent_id)
    .fetch_optional(pool)
    .await
}

/// Get agents that are not assigned to any site
pub async fn get_unassigned_agents(pool: &PgPool) -> Result<Vec<Agent>, sqlx::Error> {
    sqlx::query_as::<_, Agent>(
        "SELECT * FROM agents WHERE site_id IS NULL ORDER BY hostname"
    )
    .fetch_all(pool)
    .await
}

/// Update agent last_seen timestamp (for heartbeat)
pub async fn update_agent_last_seen(
    pool: &PgPool,
    id: Uuid,
) -> Result<(), sqlx::Error> {
    sqlx::query("UPDATE agents SET last_seen = NOW(), status = 'online' WHERE id = $1")
        .bind(id)
        .execute(pool)
        .await?;
    Ok(())
}


     1→//! Client (organization) database operations
     2→
     3→use serde::{Deserialize, Serialize};
     4→use sqlx::PgPool;
     5→use uuid::Uuid;
     6→
     7→/// Client record from database
     8→#[derive(Debug, Clone, sqlx::FromRow)]
     9→pub struct Client {
    10→    pub id: Uuid,
    11→    pub name: String,
    12→    pub code: Option<String>,
    13→    pub notes: Option<String>,
    14→    pub is_active: bool,
    15→    pub created_at: chrono::DateTime<chrono::Utc>,
    16→    pub updated_at: chrono::DateTime<chrono::Utc>,
    17→}
    18→
    19→/// Client response for API
    20→#[derive(Debug, Clone, Serialize)]
    21→pub struct ClientResponse {
    22→    pub id: Uuid,
    23→    pub name: String,
    24→    pub code: Option<String>,
    25→    pub notes: Option<String>,
    26→    pub is_active: bool,
    27→    pub created_at: chrono::DateTime<chrono::Utc>,
    28→    pub site_count: Option<i64>,
    29→    pub agent_count: Option<i64>,
    30→}
    31→
    32→impl From<Client> for ClientResponse {
    33→    fn from(c: Client) -> Self {
    34→        ClientResponse {
    35→            id: c.id,
    36→            name: c.name,
    37→            code: c.code,
    38→            notes: c.notes,
    39→            is_active: c.is_active,
    40→            created_at: c.created_at,
    41→            site_count: None,
    42→            agent_count: None,
    43→        }
    44→    }
    45→}
    46→
    47→/// Data for creating a new client
    48→#[derive(Debug, Deserialize)]
    49→pub struct CreateClient {
    50→    pub name: String,
    51→    pub code: Option<String>,
    52→    pub notes: Option<String>,
    53→}
    54→
    55→/// Data for updating a client
    56→#[derive(Debug, Deserialize)]
    57→pub struct UpdateClient {
    58→    pub name: Option<String>,
    59→    pub code: Option<String>,
    60→    pub notes: Option<String>,
    61→    pub is_active: Option<bool>,
    62→}
    63→
    64→/// Create a new client
    65→pub async fn create_client(pool: &PgPool, client: CreateClient) -> Result<Client, sqlx::Error> {
    66→    sqlx::query_as::<_, Client>(
    67→        r#"
    68→        INSERT INTO clients (name, code, notes)
    69→        VALUES ($1, $2, $3)
    70→        RETURNING *
    71→        "#,
    72→    )
    73→    .bind(&client.name)
    74→    .bind(&client.code)
    75→    .bind(&client.notes)
    76→    .fetch_one(pool)
    77→    .await
    78→}
    79→
    80→/// Get a client by ID
    81→pub async fn get_client_by_id(pool: &PgPool, id: Uuid) -> Result<Option<Client>, sqlx::Error> {
    82→    sqlx::query_as::<_, Client>("SELECT * FROM clients WHERE id = $1")
    83→        .bind(id)
    84→        .fetch_optional(pool)
    85→        .await
    86→}
    87→
    88→/// Get all clients
    89→pub async fn get_all_clients(pool: &PgPool) -> Result<Vec<Client>, sqlx::Error> {
    90→    sqlx::query_as::<_, Client>("SELECT * FROM clients ORDER BY name")
    91→        .fetch_all(pool)
    92→        .await
    93→}
    94→
    95→/// Get all clients with counts
    96→#[derive(Debug, Clone, sqlx::FromRow)]
    97→pub struct ClientWithCounts {
    98→    pub id: Uuid,
    99→    pub name: String,
   100→    pub code: Option<String>,
   101→    pub notes: Option<String>,
   102→    pub is_active: bool,
   103→    pub created_at: chrono::DateTime<chrono::Utc>,
   104→    pub updated_at: chrono::DateTime<chrono::Utc>,
   105→    pub site_count: i64,
   106→    pub agent_count: i64,
   107→}
   108→
   109→pub async fn get_all_clients_with_counts(pool: &PgPool) -> Result<Vec<ClientWithCounts>, sqlx::Error> {
   110→    sqlx::query_as::<_, ClientWithCounts>(
   111→        r#"
   112→        SELECT
   113→            c.*,
   114→            COALESCE((SELECT COUNT(*) FROM sites WHERE client_id = c.id), 0) as site_count,
   115→            COALESCE((SELECT COUNT(*) FROM agents a JOIN sites s ON a.site_id = s.id WHERE s.client_id = c.id), 0) as agent_count
   116→        FROM clients c
   117→        ORDER BY c.name
   118→        "#,
   119→    )
   120→    .fetch_all(pool)
   121→    .await
   122→}
   123→
   124→/// Update a client
   125→pub async fn update_client(
   126→    pool: &PgPool,
   127→    id: Uuid,
   128→    update: UpdateClient,
   129→) -> Result<Option<Client>, sqlx::Error> {
   130→    sqlx::query_as::<_, Client>(
   131→        r#"
   132→        UPDATE clients
   133→        SET name = COALESCE($1, name),
   134→            code = COALESCE($2, code),
   135→            notes = COALESCE($3, notes),
   136→            is_active = COALESCE($4, is_active)
   137→        WHERE id = $5
   138→        RETURNING *
   139→        "#,
   140→    )
   141→    .bind(&update.name)
   142→    .bind(&update.code)
   143→    .bind(&update.notes)
   144→    .bind(&update.is_active)
   145→    .bind(id)
   146→    .fetch_optional(pool)
   147→    .await
   148→}
   149→
   150→/// Delete a client
   151→pub async fn delete_client(pool: &PgPool, id: Uuid) -> Result<bool, sqlx::Error> {
   152→    let result = sqlx::query("DELETE FROM clients WHERE id = $1")
   153→        .bind(id)
   154→        .execute(pool)
   155→        .await?;
   156→    Ok(result.rows_affected() > 0)
   157→}
   158→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

//! Client (organization) database operations

use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use uuid::Uuid;

/// Client record from database
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct Client {
    pub id: Uuid,
    pub name: String,
    pub code: Option<String>,
    pub notes: Option<String>,
    pub is_active: bool,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

/// Client response for API
#[derive(Debug, Clone, Serialize)]
pub struct ClientResponse {
    pub id: Uuid,
    pub name: String,
    pub code: Option<String>,
    pub notes: Option<String>,
    pub is_active: bool,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub site_count: Option<i64>,
    pub agent_count: Option<i64>,
}

impl From<Client> for ClientResponse {
    fn from(c: Client) -> Self {
        ClientResponse {
            id: c.id,
            name: c.name,
            code: c.code,
            notes: c.notes,
            is_active: c.is_active,
            created_at: c.created_at,
            site_count: None,
            agent_count: None,
        }
    }
}

/// Data for creating a new client
#[derive(Debug, Deserialize)]
pub struct CreateClient {
    pub name: String,
    pub code: Option<String>,
    pub notes: Option<String>,
}

/// Data for updating a client
#[derive(Debug, Deserialize)]
pub struct UpdateClient {
    pub name: Option<String>,
    pub code: Option<String>,
    pub notes: Option<String>,
    pub is_active: Option<bool>,
}

/// Create a new client
pub async fn create_client(pool: &PgPool, client: CreateClient) -> Result<Client, sqlx::Error> {
    sqlx::query_as::<_, Client>(
        r#"
        INSERT INTO clients (name, code, notes)
        VALUES ($1, $2, $3)
        RETURNING *
        "#,
    )
    .bind(&client.name)
    .bind(&client.code)
    .bind(&client.notes)
    .fetch_one(pool)
    .await
}

/// Get a client by ID
pub async fn get_client_by_id(pool: &PgPool, id: Uuid) -> Result<Option<Client>, sqlx::Error> {
    sqlx::query_as::<_, Client>("SELECT * FROM clients WHERE id = $1")
        .bind(id)
        .fetch_optional(pool)
        .await
}

/// Get all clients
pub async fn get_all_clients(pool: &PgPool) -> Result<Vec<Client>, sqlx::Error> {
    sqlx::query_as::<_, Client>("SELECT * FROM clients ORDER BY name")
        .fetch_all(pool)
        .await
}

/// Get all clients with counts
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct ClientWithCounts {
    pub id: Uuid,
    pub name: String,
    pub code: Option<String>,
    pub notes: Option<String>,
    pub is_active: bool,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
    pub site_count: i64,
    pub agent_count: i64,
}

pub async fn get_all_clients_with_counts(pool: &PgPool) -> Result<Vec<ClientWithCounts>, sqlx::Error> {
    sqlx::query_as::<_, ClientWithCounts>(
        r#"
        SELECT
            c.*,
            COALESCE((SELECT COUNT(*) FROM sites WHERE client_id = c.id), 0) as site_count,
            COALESCE((SELECT COUNT(*) FROM agents a JOIN sites s ON a.site_id = s.id WHERE s.client_id = c.id), 0) as agent_count
        FROM clients c
        ORDER BY c.name
        "#,
    )
    .fetch_all(pool)
    .await
}

/// Update a client
pub async fn update_client(
    pool: &PgPool,
    id: Uuid,
    update: UpdateClient,
) -> Result<Option<Client>, sqlx::Error> {
    sqlx::query_as::<_, Client>(
        r#"
        UPDATE clients
        SET name = COALESCE($1, name),
            code = COALESCE($2, code),
            notes = COALESCE($3, notes),
            is_active = COALESCE($4, is_active)
        WHERE id = $5
        RETURNING *
        "#,
    )
    .bind(&update.name)
    .bind(&update.code)
    .bind(&update.notes)
    .bind(&update.is_active)
    .bind(id)
    .fetch_optional(pool)
    .await
}

/// Delete a client
pub async fn delete_client(pool: &PgPool, id: Uuid) -> Result<bool, sqlx::Error> {
    let result = sqlx::query("DELETE FROM clients WHERE id = $1")
        .bind(id)
        .execute(pool)
        .await?;
    Ok(result.rows_affected() > 0)
}


     1→//! Site database operations
     2→
     3→use rand::Rng;
     4→use serde::{Deserialize, Serialize};
     5→use sqlx::PgPool;
     6→use uuid::Uuid;
     7→
     8→/// Word lists for generating site codes
     9→const ADJECTIVES: &[&str] = &[
    10→    "BLUE", "GREEN", "RED", "GOLD", "SILVER", "IRON", "COPPER", "BRONZE",
    11→    "SWIFT", "BRIGHT", "DARK", "LIGHT", "BOLD", "CALM", "WILD", "WARM",
    12→    "NORTH", "SOUTH", "EAST", "WEST", "UPPER", "LOWER", "INNER", "OUTER",
    13→];
    14→
    15→const NOUNS: &[&str] = &[
    16→    "HAWK", "EAGLE", "TIGER", "LION", "WOLF", "BEAR", "FALCON", "PHOENIX",
    17→    "PEAK", "VALLEY", "RIVER", "OCEAN", "STORM", "CLOUD", "STAR", "MOON",
    18→    "TOWER", "BRIDGE", "GATE", "FORGE", "CASTLE", "HARBOR", "MEADOW", "GROVE",
    19→];
    20→
    21→/// Generate a human-friendly site code (e.g., "BLUE-TIGER-4829")
    22→pub fn generate_site_code() -> String {
    23→    let mut rng = rand::thread_rng();
    24→    let adj = ADJECTIVES[rng.gen_range(0..ADJECTIVES.len())];
    25→    let noun = NOUNS[rng.gen_range(0..NOUNS.len())];
    26→    let num: u16 = rng.gen_range(1000..9999);
    27→    format!("{}-{}-{}", adj, noun, num)
    28→}
    29→
    30→/// Site record from database
    31→#[derive(Debug, Clone, sqlx::FromRow)]
    32→pub struct Site {
    33→    pub id: Uuid,
    34→    pub client_id: Uuid,
    35→    pub name: String,
    36→    pub site_code: String,
    37→    pub api_key_hash: String,
    38→    pub address: Option<String>,
    39→    pub notes: Option<String>,
    40→    pub is_active: bool,
    41→    pub created_at: chrono::DateTime<chrono::Utc>,
    42→    pub updated_at: chrono::DateTime<chrono::Utc>,
    43→}
    44→
    45→/// Site response for API
    46→#[derive(Debug, Clone, Serialize)]
    47→pub struct SiteResponse {
    48→    pub id: Uuid,
    49→    pub client_id: Uuid,
    50→    pub client_name: Option<String>,
    51→    pub name: String,
    52→    pub site_code: String,
    53→    pub address: Option<String>,
    54→    pub notes: Option<String>,
    55→    pub is_active: bool,
    56→    pub created_at: chrono::DateTime<chrono::Utc>,
    57→    pub agent_count: Option<i64>,
    58→}
    59→
    60→impl From<Site> for SiteResponse {
    61→    fn from(s: Site) -> Self {
    62→        SiteResponse {
    63→            id: s.id,
    64→            client_id: s.client_id,
    65→            client_name: None,
    66→            name: s.name,
    67→            site_code: s.site_code,
    68→            address: s.address,
    69→            notes: s.notes,
    70→            is_active: s.is_active,
    71→            created_at: s.created_at,
    72→            agent_count: None,
    73→        }
    74→    }
    75→}
    76→
    77→/// Data for creating a new site
    78→#[derive(Debug, Deserialize)]
    79→pub struct CreateSite {
    80→    pub client_id: Uuid,
    81→    pub name: String,
    82→    pub address: Option<String>,
    83→    pub notes: Option<String>,
    84→}
    85→
    86→/// Internal create with all fields
    87→pub struct CreateSiteInternal {
    88→    pub client_id: Uuid,
    89→    pub name: String,
    90→    pub site_code: String,
    91→    pub api_key_hash: String,
    92→    pub address: Option<String>,
    93→    pub notes: Option<String>,
    94→}
    95→
    96→/// Data for updating a site
    97→#[derive(Debug, Deserialize)]
    98→pub struct UpdateSite {
    99→    pub name: Option<String>,
   100→    pub address: Option<String>,
   101→    pub notes: Option<String>,
   102→    pub is_active: Option<bool>,
   103→}
   104→
   105→/// Create a new site
   106→pub async fn create_site(pool: &PgPool, site: CreateSiteInternal) -> Result<Site, sqlx::Error> {
   107→    sqlx::query_as::<_, Site>(
   108→        r#"
   109→        INSERT INTO sites (client_id, name, site_code, api_key_hash, address, notes)
   110→        VALUES ($1, $2, $3, $4, $5, $6)
   111→        RETURNING *
   112→        "#,
   113→    )
   114→    .bind(&site.client_id)
   115→    .bind(&site.name)
   116→    .bind(&site.site_code)
   117→    .bind(&site.api_key_hash)
   118→    .bind(&site.address)
   119→    .bind(&site.notes)
   120→    .fetch_one(pool)
   121→    .await
   122→}
   123→
   124→/// Get a site by ID
   125→pub async fn get_site_by_id(pool: &PgPool, id: Uuid) -> Result<Option<Site>, sqlx::Error> {
   126→    sqlx::query_as::<_, Site>("SELECT * FROM sites WHERE id = $1")
   127→        .bind(id)
   128→        .fetch_optional(pool)
   129→        .await
   130→}
   131→
   132→/// Get a site by site code
   133→pub async fn get_site_by_code(pool: &PgPool, site_code: &str) -> Result<Option<Site>, sqlx::Error> {
   134→    sqlx::query_as::<_, Site>("SELECT * FROM sites WHERE site_code = $1 AND is_active = true")
   135→        .bind(site_code.to_uppercase())
   136→        .fetch_optional(pool)
   137→        .await
   138→}
   139→
   140→/// Get a site by API key hash
   141→pub async fn get_site_by_api_key_hash(pool: &PgPool, api_key_hash: &str) -> Result<Option<Site>, sqlx::Error> {
   142→    sqlx::query_as::<_, Site>("SELECT * FROM sites WHERE api_key_hash = $1 AND is_active = true")
   143→        .bind(api_key_hash)
   144→        .fetch_optional(pool)
   145→        .await
   146→}
   147→
   148→/// Get all sites for a client
   149→pub async fn get_sites_by_client(pool: &PgPool, client_id: Uuid) -> Result<Vec<Site>, sqlx::Error> {
   150→    sqlx::query_as::<_, Site>("SELECT * FROM sites WHERE client_id = $1 ORDER BY name")
   151→        .bind(client_id)
   152→        .fetch_all(pool)
   153→        .await
   154→}
   155→
   156→/// Get all sites
   157→pub async fn get_all_sites(pool: &PgPool) -> Result<Vec<Site>, sqlx::Error> {
   158→    sqlx::query_as::<_, Site>("SELECT * FROM sites ORDER BY name")
   159→        .fetch_all(pool)
   160→        .await
   161→}
   162→
   163→/// Site with client name and agent count
   164→#[derive(Debug, Clone, sqlx::FromRow)]
   165→pub struct SiteWithDetails {
   166→    pub id: Uuid,
   167→    pub client_id: Uuid,
   168→    pub name: String,
   169→    pub site_code: String,
   170→    pub api_key_hash: String,
   171→    pub address: Option<String>,
   172→    pub notes: Option<String>,
   173→    pub is_active: bool,
   174→    pub created_at: chrono::DateTime<chrono::Utc>,
   175→    pub updated_at: chrono::DateTime<chrono::Utc>,
   176→    pub client_name: String,
   177→    pub agent_count: i64,
   178→}
   179→
   180→pub async fn get_all_sites_with_details(pool: &PgPool) -> Result<Vec<SiteWithDetails>, sqlx::Error> {
   181→    sqlx::query_as::<_, SiteWithDetails>(
   182→        r#"
   183→        SELECT
   184→            s.*,
   185→            c.name as client_name,
   186→            COALESCE((SELECT COUNT(*) FROM agents WHERE site_id = s.id), 0) as agent_count
   187→        FROM sites s
   188→        JOIN clients c ON s.client_id = c.id
   189→        ORDER BY c.name, s.name
   190→        "#,
   191→    )
   192→    .fetch_all(pool)
   193→    .await
   194→}
   195→
   196→/// Update a site
   197→pub async fn update_site(
   198→    pool: &PgPool,
   199→    id: Uuid,
   200→    update: UpdateSite,
   201→) -> Result<Option<Site>, sqlx::Error> {
   202→    sqlx::query_as::<_, Site>(
   203→        r#"
   204→        UPDATE sites
   205→        SET name = COALESCE($1, name),
   206→            address = COALESCE($2, address),
   207→            notes = COALESCE($3, notes),
   208→            is_active = COALESCE($4, is_active)
   209→        WHERE id = $5
   210→        RETURNING *
   211→        "#,
   212→    )
   213→    .bind(&update.name)
   214→    .bind(&update.address)
   215→    .bind(&update.notes)
   216→    .bind(&update.is_active)
   217→    .bind(id)
   218→    .fetch_optional(pool)
   219→    .await
   220→}
   221→
   222→/// Regenerate API key for a site
   223→pub async fn regenerate_site_api_key(
   224→    pool: &PgPool,
   225→    id: Uuid,
   226→    new_api_key_hash: &str,
   227→) -> Result<bool, sqlx::Error> {
   228→    let result = sqlx::query("UPDATE sites SET api_key_hash = $1 WHERE id = $2")
   229→        .bind(new_api_key_hash)
   230→        .bind(id)
   231→        .execute(pool)
   232→        .await?;
   233→    Ok(result.rows_affected() > 0)
   234→}
   235→
   236→/// Delete a site
   237→pub async fn delete_site(pool: &PgPool, id: Uuid) -> Result<bool, sqlx::Error> {
   238→    let result = sqlx::query("DELETE FROM sites WHERE id = $1")
   239→        .bind(id)
   240→        .execute(pool)
   241→        .await?;
   242→    Ok(result.rows_affected() > 0)
   243→}
   244→
   245→/// Check if a site code is unique
   246→pub async fn is_site_code_unique(pool: &PgPool, site_code: &str) -> Result<bool, sqlx::Error> {
   247→    let result: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM sites WHERE site_code = $1")
   248→        .bind(site_code.to_uppercase())
   249→        .fetch_one(pool)
   250→        .await?;
   251→    Ok(result.0 == 0)
   252→}
   253→
   254→/// Generate a unique site code (tries up to 10 times)
   255→pub async fn generate_unique_site_code(pool: &PgPool) -> Result<String, sqlx::Error> {
   256→    for _ in 0..10 {
   257→        let code = generate_site_code();
   258→        if is_site_code_unique(pool, &code).await? {
   259→            return Ok(code);
   260→        }
   261→    }
   262→    // Fallback: add random suffix
   263→    Ok(format!("{}-{}", generate_site_code(), rand::thread_rng().gen_range(100..999)))
   264→}
   265→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

//! Site database operations

use rand::Rng;
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use uuid::Uuid;

/// Word lists for generating site codes
const ADJECTIVES: &[&str] = &[
    "BLUE", "GREEN", "RED", "GOLD", "SILVER", "IRON", "COPPER", "BRONZE",
    "SWIFT", "BRIGHT", "DARK", "LIGHT", "BOLD", "CALM", "WILD", "WARM",
    "NORTH", "SOUTH", "EAST", "WEST", "UPPER", "LOWER", "INNER", "OUTER",
];

const NOUNS: &[&str] = &[
    "HAWK", "EAGLE", "TIGER", "LION", "WOLF", "BEAR", "FALCON", "PHOENIX",
    "PEAK", "VALLEY", "RIVER", "OCEAN", "STORM", "CLOUD", "STAR", "MOON",
    "TOWER", "BRIDGE", "GATE", "FORGE", "CASTLE", "HARBOR", "MEADOW", "GROVE",
];

/// Generate a human-friendly site code (e.g., "BLUE-TIGER-4829")
pub fn generate_site_code() -> String {
    let mut rng = rand::thread_rng();
    let adj = ADJECTIVES[rng.gen_range(0..ADJECTIVES.len())];
    let noun = NOUNS[rng.gen_range(0..NOUNS.len())];
    let num: u16 = rng.gen_range(1000..9999);
    format!("{}-{}-{}", adj, noun, num)
}

/// Site record from database
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct Site {
    pub id: Uuid,
    pub client_id: Uuid,
    pub name: String,
    pub site_code: String,
    pub api_key_hash: String,
    pub address: Option<String>,
    pub notes: Option<String>,
    pub is_active: bool,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

/// Site response for API
#[derive(Debug, Clone, Serialize)]
pub struct SiteResponse {
    pub id: Uuid,
    pub client_id: Uuid,
    pub client_name: Option<String>,
    pub name: String,
    pub site_code: String,
    pub address: Option<String>,
    pub notes: Option<String>,
    pub is_active: bool,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub agent_count: Option<i64>,
}

impl From<Site> for SiteResponse {
    fn from(s: Site) -> Self {
        SiteResponse {
            id: s.id,
            client_id: s.client_id,
            client_name: None,
            name: s.name,
            site_code: s.site_code,
            address: s.address,
            notes: s.notes,
            is_active: s.is_active,
            created_at: s.created_at,
            agent_count: None,
        }
    }
}

/// Data for creating a new site
#[derive(Debug, Deserialize)]
pub struct CreateSite {
    pub client_id: Uuid,
    pub name: String,
    pub address: Option<String>,
    pub notes: Option<String>,
}

/// Internal create with all fields
pub struct CreateSiteInternal {
    pub client_id: Uuid,
    pub name: String,
    pub site_code: String,
    pub api_key_hash: String,
    pub address: Option<String>,
    pub notes: Option<String>,
}

/// Data for updating a site
#[derive(Debug, Deserialize)]
pub struct UpdateSite {
    pub name: Option<String>,
    pub address: Option<String>,
    pub notes: Option<String>,
    pub is_active: Option<bool>,
}

/// Create a new site
pub async fn create_site(pool: &PgPool, site: CreateSiteInternal) -> Result<Site, sqlx::Error> {
    sqlx::query_as::<_, Site>(
        r#"
        INSERT INTO sites (client_id, name, site_code, api_key_hash, address, notes)
        VALUES ($1, $2, $3, $4, $5, $6)
        RETURNING *
        "#,
    )
    .bind(&site.client_id)
    .bind(&site.name)
    .bind(&site.site_code)
    .bind(&site.api_key_hash)
    .bind(&site.address)
    .bind(&site.notes)
    .fetch_one(pool)
    .await
}

/// Get a site by ID
pub async fn get_site_by_id(pool: &PgPool, id: Uuid) -> Result<Option<Site>, sqlx::Error> {
    sqlx::query_as::<_, Site>("SELECT * FROM sites WHERE id = $1")
        .bind(id)
        .fetch_optional(pool)
        .await
}

/// Get a site by site code
pub async fn get_site_by_code(pool: &PgPool, site_code: &str) -> Result<Option<Site>, sqlx::Error> {
    sqlx::query_as::<_, Site>("SELECT * FROM sites WHERE site_code = $1 AND is_active = true")
        .bind(site_code.to_uppercase())
        .fetch_optional(pool)
        .await
}

/// Get a site by API key hash
pub async fn get_site_by_api_key_hash(pool: &PgPool, api_key_hash: &str) -> Result<Option<Site>, sqlx::Error> {
    sqlx::query_as::<_, Site>("SELECT * FROM sites WHERE api_key_hash = $1 AND is_active = true")
        .bind(api_key_hash)
        .fetch_optional(pool)
        .await
}

/// Get all sites for a client
pub async fn get_sites_by_client(pool: &PgPool, client_id: Uuid) -> Result<Vec<Site>, sqlx::Error> {
    sqlx::query_as::<_, Site>("SELECT * FROM sites WHERE client_id = $1 ORDER BY name")
        .bind(client_id)
        .fetch_all(pool)
        .await
}

/// Get all sites
pub async fn get_all_sites(pool: &PgPool) -> Result<Vec<Site>, sqlx::Error> {
    sqlx::query_as::<_, Site>("SELECT * FROM sites ORDER BY name")
        .fetch_all(pool)
        .await
}

/// Site with client name and agent count
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct SiteWithDetails {
    pub id: Uuid,
    pub client_id: Uuid,
    pub name: String,
    pub site_code: String,
    pub api_key_hash: String,
    pub address: Option<String>,
    pub notes: Option<String>,
    pub is_active: bool,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
    pub client_name: String,
    pub agent_count: i64,
}

pub async fn get_all_sites_with_details(pool: &PgPool) -> Result<Vec<SiteWithDetails>, sqlx::Error> {
    sqlx::query_as::<_, SiteWithDetails>(
        r#"
        SELECT
            s.*,
            c.name as client_name,
            COALESCE((SELECT COUNT(*) FROM agents WHERE site_id = s.id), 0) as agent_count
        FROM sites s
        JOIN clients c ON s.client_id = c.id
        ORDER BY c.name, s.name
        "#,
    )
    .fetch_all(pool)
    .await
}

/// Update a site
pub async fn update_site(
    pool: &PgPool,
    id: Uuid,
    update: UpdateSite,
) -> Result<Option<Site>, sqlx::Error> {
    sqlx::query_as::<_, Site>(
        r#"
        UPDATE sites
        SET name = COALESCE($1, name),
            address = COALESCE($2, address),
            notes = COALESCE($3, notes),
            is_active = COALESCE($4, is_active)
        WHERE id = $5
        RETURNING *
        "#,
    )
    .bind(&update.name)
    .bind(&update.address)
    .bind(&update.notes)
    .bind(&update.is_active)
    .bind(id)
    .fetch_optional(pool)
    .await
}

/// Regenerate API key for a site
pub async fn regenerate_site_api_key(
    pool: &PgPool,
    id: Uuid,
    new_api_key_hash: &str,
) -> Result<bool, sqlx::Error> {
    let result = sqlx::query("UPDATE sites SET api_key_hash = $1 WHERE id = $2")
        .bind(new_api_key_hash)
        .bind(id)
        .execute(pool)
        .await?;
    Ok(result.rows_affected() > 0)
}

/// Delete a site
pub async fn delete_site(pool: &PgPool, id: Uuid) -> Result<bool, sqlx::Error> {
    let result = sqlx::query("DELETE FROM sites WHERE id = $1")
        .bind(id)
        .execute(pool)
        .await?;
    Ok(result.rows_affected() > 0)
}

/// Check if a site code is unique
pub async fn is_site_code_unique(pool: &PgPool, site_code: &str) -> Result<bool, sqlx::Error> {
    let result: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM sites WHERE site_code = $1")
        .bind(site_code.to_uppercase())
        .fetch_one(pool)
        .await?;
    Ok(result.0 == 0)
}

/// Generate a unique site code (tries up to 10 times)
pub async fn generate_unique_site_code(pool: &PgPool) -> Result<String, sqlx::Error> {
    for _ in 0..10 {
        let code = generate_site_code();
        if is_site_code_unique(pool, &code).await? {
            return Ok(code);
        }
    }
    // Fallback: add random suffix
    Ok(format!("{}-{}", generate_site_code(), rand::thread_rng().gen_range(100..999)))
}


Now let me check the remaining migrations and look at the mod.rs to see what other configuration patterns exist:


     1→-- Agent update tracking
     2→-- Tracks update commands sent to agents and their results
     3→
     4→CREATE TABLE agent_updates (
     5→    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
     6→    agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
     7→    update_id UUID NOT NULL UNIQUE,
     8→    old_version VARCHAR(50) NOT NULL,
     9→    target_version VARCHAR(50) NOT NULL,
    10→    status VARCHAR(20) DEFAULT 'pending',  -- pending, downloading, installing, completed, failed, rolled_back
    11→    download_url TEXT,
    12→    checksum_sha256 VARCHAR(64),
    13→    started_at TIMESTAMPTZ DEFAULT NOW(),
    14→    completed_at TIMESTAMPTZ,
    15→    error_message TEXT,
    16→    created_at TIMESTAMPTZ DEFAULT NOW()
    17→);
    18→
    19→-- Index for finding updates by agent
    20→CREATE INDEX idx_agent_updates_agent ON agent_updates(agent_id);
    21→
    22→-- Index for finding updates by status (for monitoring)
    23→CREATE INDEX idx_agent_updates_status ON agent_updates(status);
    24→
    25→-- Index for finding pending/in-progress updates (for timeout detection)
    26→CREATE INDEX idx_agent_updates_pending ON agent_updates(agent_id, status)
    27→    WHERE status IN ('pending', 'downloading', 'installing');
    28→
    29→-- Add architecture column to agents table for proper binary matching
    30→ALTER TABLE agents ADD COLUMN IF NOT EXISTS architecture VARCHAR(20) DEFAULT 'amd64';
    31→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

-- Agent update tracking
-- Tracks update commands sent to agents and their results

CREATE TABLE agent_updates (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
    update_id UUID NOT NULL UNIQUE,
    old_version VARCHAR(50) NOT NULL,
    target_version VARCHAR(50) NOT NULL,
    status VARCHAR(20) DEFAULT 'pending',  -- pending, downloading, installing, completed, failed, rolled_back
    download_url TEXT,
    checksum_sha256 VARCHAR(64),
    started_at TIMESTAMPTZ DEFAULT NOW(),
    completed_at TIMESTAMPTZ,
    error_message TEXT,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Index for finding updates by agent
CREATE INDEX idx_agent_updates_agent ON agent_updates(agent_id);

-- Index for finding updates by status (for monitoring)
CREATE INDEX idx_agent_updates_status ON agent_updates(status);

-- Index for finding pending/in-progress updates (for timeout detection)
CREATE INDEX idx_agent_updates_pending ON agent_updates(agent_id, status)
    WHERE status IN ('pending', 'downloading', 'installing');

-- Add architecture column to agents table for proper binary matching
ALTER TABLE agents ADD COLUMN IF NOT EXISTS architecture VARCHAR(20) DEFAULT 'amd64';


     1→-- Add temperature metrics columns to metrics table
     2→-- CPU and GPU temperatures as primary metrics, plus JSON array for all sensors
     3→
     4→ALTER TABLE metrics ADD COLUMN cpu_temp_celsius REAL;
     5→ALTER TABLE metrics ADD COLUMN gpu_temp_celsius REAL;
     6→ALTER TABLE metrics ADD COLUMN temperatures JSONB;
     7→
     8→-- Add index for querying high temperature events
     9→CREATE INDEX idx_metrics_cpu_temp ON metrics(cpu_temp_celsius) WHERE cpu_temp_celsius IS NOT NULL;
    10→
    11→COMMENT ON COLUMN metrics.cpu_temp_celsius IS 'Average CPU temperature in Celsius';
    12→COMMENT ON COLUMN metrics.gpu_temp_celsius IS 'Primary GPU temperature in Celsius';
    13→COMMENT ON COLUMN metrics.temperatures IS 'All temperature sensor readings as JSON array';
    14→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

-- Add temperature metrics columns to metrics table
-- CPU and GPU temperatures as primary metrics, plus JSON array for all sensors

ALTER TABLE metrics ADD COLUMN cpu_temp_celsius REAL;
ALTER TABLE metrics ADD COLUMN gpu_temp_celsius REAL;
ALTER TABLE metrics ADD COLUMN temperatures JSONB;

-- Add index for querying high temperature events
CREATE INDEX idx_metrics_cpu_temp ON metrics(cpu_temp_celsius) WHERE cpu_temp_celsius IS NOT NULL;

COMMENT ON COLUMN metrics.cpu_temp_celsius IS 'Average CPU temperature in Celsius';
COMMENT ON COLUMN metrics.gpu_temp_celsius IS 'Primary GPU temperature in Celsius';
COMMENT ON COLUMN metrics.temperatures IS 'All temperature sensor readings as JSON array';


     1→//! Database models and queries
     2→//!
     3→//! Provides database access for clients, sites, agents, metrics, commands, users, and updates.
     4→
     5→pub mod agents;
     6→pub mod clients;
     7→pub mod commands;
     8→pub mod metrics;
     9→pub mod sites;
    10→pub mod updates;
    11→pub mod users;
    12→
    13→pub use agents::*;
    14→pub use clients::*;
    15→pub use commands::*;
    16→pub use metrics::*;
    17→pub use sites::*;
    18→pub use updates::*;
    19→pub use users::*;
    20→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

//! Database models and queries
//!
//! Provides database access for clients, sites, agents, metrics, commands, users, and updates.

pub mod agents;
pub mod clients;
pub mod commands;
pub mod metrics;
pub mod sites;
pub mod updates;
pub mod users;

pub use agents::*;
pub use clients::*;
pub use commands::*;
pub use metrics::*;
pub use sites::*;
pub use updates::*;
pub use users::*;


Let me also check the commands.rs to see if there's an existing pattern for storing commands/configurations:


     1→//! Commands database operations
     2→
     3→use chrono::{DateTime, Utc};
     4→use serde::{Deserialize, Serialize};
     5→use sqlx::PgPool;
     6→use uuid::Uuid;
     7→
     8→/// Command record from database
     9→#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
    10→pub struct Command {
    11→    pub id: Uuid,
    12→    pub agent_id: Uuid,
    13→    pub command_type: String,
    14→    pub command_text: String,
    15→    pub status: String,
    16→    pub exit_code: Option<i32>,
    17→    pub stdout: Option<String>,
    18→    pub stderr: Option<String>,
    19→    pub created_at: DateTime<Utc>,
    20→    pub started_at: Option<DateTime<Utc>>,
    21→    pub completed_at: Option<DateTime<Utc>>,
    22→    pub created_by: Option<Uuid>,
    23→}
    24→
    25→/// Create a new command
    26→#[derive(Debug, Clone, Deserialize)]
    27→pub struct CreateCommand {
    28→    pub agent_id: Uuid,
    29→    pub command_type: String,
    30→    pub command_text: String,
    31→    pub created_by: Option<Uuid>,
    32→}
    33→
    34→/// Insert a new command
    35→pub async fn create_command(pool: &PgPool, cmd: CreateCommand) -> Result<Command, sqlx::Error> {
    36→    sqlx::query_as::<_, Command>(
    37→        r#"
    38→        INSERT INTO commands (agent_id, command_type, command_text, status, created_by)
    39→        VALUES ($1, $2, $3, 'pending', $4)
    40→        RETURNING *
    41→        "#,
    42→    )
    43→    .bind(cmd.agent_id)
    44→    .bind(&cmd.command_type)
    45→    .bind(&cmd.command_text)
    46→    .bind(cmd.created_by)
    47→    .fetch_one(pool)
    48→    .await
    49→}
    50→
    51→/// Get a command by ID
    52→pub async fn get_command_by_id(pool: &PgPool, id: Uuid) -> Result<Option<Command>, sqlx::Error> {
    53→    sqlx::query_as::<_, Command>("SELECT * FROM commands WHERE id = $1")
    54→        .bind(id)
    55→        .fetch_optional(pool)
    56→        .await
    57→}
    58→
    59→/// Get pending commands for an agent
    60→pub async fn get_pending_commands(
    61→    pool: &PgPool,
    62→    agent_id: Uuid,
    63→) -> Result<Vec<Command>, sqlx::Error> {
    64→    sqlx::query_as::<_, Command>(
    65→        r#"
    66→        SELECT * FROM commands
    67→        WHERE agent_id = $1 AND status = 'pending'
    68→        ORDER BY created_at ASC
    69→        "#,
    70→    )
    71→    .bind(agent_id)
    72→    .fetch_all(pool)
    73→    .await
    74→}
    75→
    76→/// Get command history for an agent
    77→pub async fn get_agent_commands(
    78→    pool: &PgPool,
    79→    agent_id: Uuid,
    80→    limit: i64,
    81→) -> Result<Vec<Command>, sqlx::Error> {
    82→    sqlx::query_as::<_, Command>(
    83→        r#"
    84→        SELECT * FROM commands
    85→        WHERE agent_id = $1
    86→        ORDER BY created_at DESC
    87→        LIMIT $2
    88→        "#,
    89→    )
    90→    .bind(agent_id)
    91→    .bind(limit)
    92→    .fetch_all(pool)
    93→    .await
    94→}
    95→
    96→/// Get all recent commands
    97→pub async fn get_recent_commands(pool: &PgPool, limit: i64) -> Result<Vec<Command>, sqlx::Error> {
    98→    sqlx::query_as::<_, Command>(
    99→        r#"
   100→        SELECT * FROM commands
   101→        ORDER BY created_at DESC
   102→        LIMIT $1
   103→        "#,
   104→    )
   105→    .bind(limit)
   106→    .fetch_all(pool)
   107→    .await
   108→}
   109→
   110→/// Update command status to running
   111→pub async fn mark_command_running(pool: &PgPool, id: Uuid) -> Result<(), sqlx::Error> {
   112→    sqlx::query("UPDATE commands SET status = 'running', started_at = NOW() WHERE id = $1")
   113→        .bind(id)
   114→        .execute(pool)
   115→        .await?;
   116→    Ok(())
   117→}
   118→
   119→/// Update command result
   120→#[derive(Debug, Clone, Deserialize)]
   121→pub struct CommandResult {
   122→    pub exit_code: i32,
   123→    pub stdout: String,
   124→    pub stderr: String,
   125→}
   126→
   127→pub async fn update_command_result(
   128→    pool: &PgPool,
   129→    id: Uuid,
   130→    result: CommandResult,
   131→) -> Result<(), sqlx::Error> {
   132→    let status = if result.exit_code == 0 {
   133→        "completed"
   134→    } else {
   135→        "failed"
   136→    };
   137→
   138→    sqlx::query(
   139→        r#"
   140→        UPDATE commands
   141→        SET status = $1, exit_code = $2, stdout = $3, stderr = $4, completed_at = NOW()
   142→        WHERE id = $5
   143→        "#,
   144→    )
   145→    .bind(status)
   146→    .bind(result.exit_code)
   147→    .bind(&result.stdout)
   148→    .bind(&result.stderr)
   149→    .bind(id)
   150→    .execute(pool)
   151→    .await?;
   152→
   153→    Ok(())
   154→}
   155→
   156→/// Delete a command
   157→pub async fn delete_command(pool: &PgPool, id: Uuid) -> Result<bool, sqlx::Error> {
   158→    let result = sqlx::query("DELETE FROM commands WHERE id = $1")
   159→        .bind(id)
   160→        .execute(pool)
   161→        .await?;
   162→    Ok(result.rows_affected() > 0)
   163→}
   164→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

//! Commands database operations

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use uuid::Uuid;

/// Command record from database
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct Command {
    pub id: Uuid,
    pub agent_id: Uuid,
    pub command_type: String,
    pub command_text: String,
    pub status: String,
    pub exit_code: Option<i32>,
    pub stdout: Option<String>,
    pub stderr: Option<String>,
    pub created_at: DateTime<Utc>,
    pub started_at: Option<DateTime<Utc>>,
    pub completed_at: Option<DateTime<Utc>>,
    pub created_by: Option<Uuid>,
}

/// Create a new command
#[derive(Debug, Clone, Deserialize)]
pub struct CreateCommand {
    pub agent_id: Uuid,
    pub command_type: String,
    pub command_text: String,
    pub created_by: Option<Uuid>,
}

/// Insert a new command
pub async fn create_command(pool: &PgPool, cmd: CreateCommand) -> Result<Command, sqlx::Error> {
    sqlx::query_as::<_, Command>(
        r#"
        INSERT INTO commands (agent_id, command_type, command_text, status, created_by)
        VALUES ($1, $2, $3, 'pending', $4)
        RETURNING *
        "#,
    )
    .bind(cmd.agent_id)
    .bind(&cmd.command_type)
    .bind(&cmd.command_text)
    .bind(cmd.created_by)
    .fetch_one(pool)
    .await
}

/// Get a command by ID
pub async fn get_command_by_id(pool: &PgPool, id: Uuid) -> Result<Option<Command>, sqlx::Error> {
    sqlx::query_as::<_, Command>("SELECT * FROM commands WHERE id = $1")
        .bind(id)
        .fetch_optional(pool)
        .await
}

/// Get pending commands for an agent
pub async fn get_pending_commands(
    pool: &PgPool,
    agent_id: Uuid,
) -> Result<Vec<Command>, sqlx::Error> {
    sqlx::query_as::<_, Command>(
        r#"
        SELECT * FROM commands
        WHERE agent_id = $1 AND status = 'pending'
        ORDER BY created_at ASC
        "#,
    )
    .bind(agent_id)
    .fetch_all(pool)
    .await
}

/// Get command history for an agent
pub async fn get_agent_commands(
    pool: &PgPool,
    agent_id: Uuid,
    limit: i64,
) -> Result<Vec<Command>, sqlx::Error> {
    sqlx::query_as::<_, Command>(
        r#"
        SELECT * FROM commands
        WHERE agent_id = $1
        ORDER BY created_at DESC
        LIMIT $2
        "#,
    )
    .bind(agent_id)
    .bind(limit)
    .fetch_all(pool)
    .await
}

/// Get all recent commands
pub async fn get_recent_commands(pool: &PgPool, limit: i64) -> Result<Vec<Command>, sqlx::Error> {
    sqlx::query_as::<_, Command>(
        r#"
        SELECT * FROM commands
        ORDER BY created_at DESC
        LIMIT $1
        "#,
    )
    .bind(limit)
    .fetch_all(pool)
    .await
}

/// Update command status to running
pub async fn mark_command_running(pool: &PgPool, id: Uuid) -> Result<(), sqlx::Error> {
    sqlx::query("UPDATE commands SET status = 'running', started_at = NOW() WHERE id = $1")
        .bind(id)
        .execute(pool)
        .await?;
    Ok(())
}

/// Update command result
#[derive(Debug, Clone, Deserialize)]
pub struct CommandResult {
    pub exit_code: i32,
    pub stdout: String,
    pub stderr: String,
}

pub async fn update_command_result(
    pool: &PgPool,
    id: Uuid,
    result: CommandResult,
) -> Result<(), sqlx::Error> {
    let status = if result.exit_code == 0 {
        "completed"
    } else {
        "failed"
    };

    sqlx::query(
        r#"
        UPDATE commands
        SET status = $1, exit_code = $2, stdout = $3, stderr = $4, completed_at = NOW()
        WHERE id = $5
        "#,
    )
    .bind(status)
    .bind(result.exit_code)
    .bind(&result.stdout)
    .bind(&result.stderr)
    .bind(id)
    .execute(pool)
    .await?;

    Ok(())
}

/// Delete a command
pub async fn delete_command(pool: &PgPool, id: Uuid) -> Result<bool, sqlx::Error> {
    let result = sqlx::query("DELETE FROM commands WHERE id = $1")
        .bind(id)
        .execute(pool)
        .await?;
    Ok(result.rows_affected() > 0)
}