-- Audit log table for tracking command execution history
CREATE TABLE IF NOT EXISTS audit_log (
    id               TEXT PRIMARY KEY,
    api_key_id       TEXT NOT NULL,
    command_id       TEXT NOT NULL,
    project_id       TEXT NOT NULL,
    command_type     TEXT NOT NULL,
    args             TEXT,
    client_ip        TEXT,
    user_agent       TEXT,
    started_at       TIMESTAMPTZ NOT NULL,
    completed_at     TIMESTAMPTZ,
    exit_code        INTEGER,
    duration_ms      INTEGER,
    status           TEXT DEFAULT 'running',
    error_message    TEXT,
    output_size_bytes INTEGER DEFAULT 0,
    created_at       TIMESTAMPTZ DEFAULT NOW()
);

-- Index for querying by API key (e.g., "show me all commands from this key")
CREATE INDEX IF NOT EXISTS idx_audit_api_key ON audit_log(api_key_id, created_at DESC);

-- Index for querying by project (e.g., "show me all commands for this project")
CREATE INDEX IF NOT EXISTS idx_audit_project ON audit_log(project_id, created_at DESC);

-- Index for looking up by command ID (for updating completion status)
CREATE INDEX IF NOT EXISTS idx_audit_command ON audit_log(command_id);

-- Index for filtering by status
CREATE INDEX IF NOT EXISTS idx_audit_status ON audit_log(status, created_at DESC);

COMMENT ON TABLE audit_log IS 'Persistent audit log for all command executions';
COMMENT ON COLUMN audit_log.api_key_id IS 'ID of the API key that initiated the command';
COMMENT ON COLUMN audit_log.command_id IS 'Unique identifier for the command execution';
COMMENT ON COLUMN audit_log.project_id IS 'Project/pod where command was executed';
COMMENT ON COLUMN audit_log.command_type IS 'Type: claude, shell, or git';
COMMENT ON COLUMN audit_log.args IS 'JSON-encoded command arguments';
COMMENT ON COLUMN audit_log.status IS 'running, success, error, or cancelled';
COMMENT ON COLUMN audit_log.output_size_bytes IS 'Total size of command output in bytes';
