-- GuruRMM Tunnel Sessions Schema
-- Creates tables for technician SSH tunnel sessions and audit logging

-- Tech Sessions table
-- Stores active and historical SSH tunnel sessions between technicians and agents
CREATE TABLE tech_sessions (
    id SERIAL PRIMARY KEY,
    session_id VARCHAR(36) UNIQUE NOT NULL,
    tech_id INTEGER NOT NULL,
    agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
    opened_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    last_activity TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    closed_at TIMESTAMPTZ,
    status VARCHAR(20) NOT NULL DEFAULT 'active',
    CONSTRAINT unique_active_session UNIQUE (tech_id, agent_id, status)
        WHERE status = 'active'
);

-- Index for finding sessions by technician
CREATE INDEX idx_tech_sessions_tech ON tech_sessions(tech_id);

-- Index for finding sessions by agent
CREATE INDEX idx_tech_sessions_agent ON tech_sessions(agent_id);

-- Index for filtering by session status
CREATE INDEX idx_tech_sessions_status ON tech_sessions(status);

-- Tunnel Audit table
-- Detailed audit log for all tunnel operations and channel activity
CREATE TABLE tunnel_audit (
    id BIGSERIAL PRIMARY KEY,
    session_id VARCHAR(36) NOT NULL REFERENCES tech_sessions(session_id) ON DELETE CASCADE,
    channel_id VARCHAR(36) NOT NULL,
    operation VARCHAR(50) NOT NULL,
    details JSONB,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Index for querying audit logs by session
CREATE INDEX idx_tunnel_audit_session ON tunnel_audit(session_id);

-- Index for time-based audit queries
CREATE INDEX idx_tunnel_audit_created ON tunnel_audit(created_at);
