-- FTS5 跨会话全文搜索
-- 在 agent_sessions 和 agent_messages 上创建虚拟表，支持 BM25 排序搜索。

CREATE VIRTUAL TABLE IF NOT EXISTS agent_sessions_fts USING fts5(
    session_id,
    title,
    summary,
    metadata,
    content='agent_sessions',
    content_rowid='rowid'
);

CREATE VIRTUAL TABLE IF NOT EXISTS agent_messages_fts USING fts5(
    session_id,
    role,
    content,
    thought,
    tool_calls,
    content='agent_messages',
    content_rowid='rowid'
);

-- Triggers: sessions
CREATE TRIGGER IF NOT EXISTS sessions_fts_insert AFTER INSERT ON agent_sessions
BEGIN
    INSERT INTO agent_sessions_fts(session_id, title, summary, metadata)
    VALUES (NEW.session_id, NEW.title, NEW.summary, NEW.metadata);
END;

CREATE TRIGGER IF NOT EXISTS sessions_fts_update AFTER UPDATE ON agent_sessions
BEGIN
    UPDATE agent_sessions_fts SET
        session_id = NEW.session_id,
        title = NEW.title,
        summary = NEW.summary,
        metadata = NEW.metadata
    WHERE rowid = OLD.rowid;
END;

CREATE TRIGGER IF NOT EXISTS sessions_fts_delete AFTER DELETE ON agent_sessions
BEGIN
    DELETE FROM agent_sessions_fts WHERE rowid = OLD.rowid;
END;

-- Triggers: messages
CREATE TRIGGER IF NOT EXISTS messages_fts_insert AFTER INSERT ON agent_messages
BEGIN
    INSERT INTO agent_messages_fts(session_id, role, content, thought, tool_calls)
    VALUES (NEW.session_id, NEW.role, NEW.content, NEW.thought, NEW.tool_calls);
END;

CREATE TRIGGER IF NOT EXISTS messages_fts_update AFTER UPDATE ON agent_messages
BEGIN
    UPDATE agent_messages_fts SET
        session_id = NEW.session_id,
        role = NEW.role,
        content = NEW.content,
        thought = NEW.thought,
        tool_calls = NEW.tool_calls
    WHERE rowid = OLD.rowid;
END;

CREATE TRIGGER IF NOT EXISTS messages_fts_delete AFTER DELETE ON agent_messages
BEGIN
    DELETE FROM agent_messages_fts WHERE rowid = OLD.rowid;
END;

-- 回填已有数据
INSERT OR IGNORE INTO agent_sessions_fts(session_id, title, summary, metadata)
SELECT session_id, title, summary, metadata FROM agent_sessions;

INSERT OR IGNORE INTO agent_messages_fts(session_id, role, content, thought, tool_calls)
SELECT session_id, role, content, thought, tool_calls FROM agent_messages;
