-- Migration: Add Performance Metrics and Event Logging Tables
-- Description: Creates tables for tracking performance metrics and event logging for agentic RAG

-- Performance metrics tracking
CREATE TABLE performance_metrics (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    session_id UUID REFERENCES agentic_rag_sessions(id) ON DELETE CASCADE,
    metric_type VARCHAR(50) NOT NULL CHECK (metric_type IN ('processing_time', 'api_calls', 'cost', 'memory_usage', 'cpu_usage')),
    metric_value DECIMAL(10,4) NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
);

-- Session events for audit trail
CREATE TABLE session_events (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    session_id UUID REFERENCES agentic_rag_sessions(id) ON DELETE CASCADE,
    event_type VARCHAR(100) NOT NULL,
    event_data JSONB,
    created_at TIMESTAMP DEFAULT NOW()
);

-- Execution events for audit trail
CREATE TABLE execution_events (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    execution_id UUID REFERENCES agent_executions(id) ON DELETE CASCADE,
    event_type VARCHAR(100) NOT NULL,
    event_data JSONB,
    created_at TIMESTAMP DEFAULT NOW()
);

-- Create indexes for better performance
CREATE INDEX idx_performance_metrics_session_id ON performance_metrics(session_id);
CREATE INDEX idx_performance_metrics_metric_type ON performance_metrics(metric_type);
CREATE INDEX idx_performance_metrics_created_at ON performance_metrics(created_at);

CREATE INDEX idx_session_events_session_id ON session_events(session_id);
CREATE INDEX idx_session_events_event_type ON session_events(event_type);
CREATE INDEX idx_session_events_created_at ON session_events(created_at);

CREATE INDEX idx_execution_events_execution_id ON execution_events(execution_id);
CREATE INDEX idx_execution_events_event_type ON execution_events(event_type);
CREATE INDEX idx_execution_events_created_at ON execution_events(created_at);

-- Add comments for documentation
COMMENT ON TABLE performance_metrics IS 'Tracks performance metrics for agentic RAG sessions';
COMMENT ON TABLE session_events IS 'Audit trail for session-level events';
COMMENT ON TABLE execution_events IS 'Audit trail for execution-level events'; 