-- 修复 FTS5 全文搜索中虚拟表与原始物理表的 rowid 不一致问题
-- 增量迁移：删除旧触发器，以正确映射 rowid 的触发器替代，并重建现有 FTS5 数据

-- 1. 删除旧的不安全触发器
DROP TRIGGER IF EXISTS sessions_fts_insert;
DROP TRIGGER IF EXISTS messages_fts_insert;

-- 2. 重新创建指定 rowid 列的插入触发器，确保 FTS 行 ID 与原始物理表行 ID 完全一致
CREATE TRIGGER IF NOT EXISTS sessions_fts_insert AFTER INSERT ON agent_sessions
BEGIN
    INSERT INTO agent_sessions_fts(rowid, session_id, title, summary, metadata)
    VALUES (NEW.rowid, NEW.session_id, NEW.title, NEW.summary, NEW.metadata);
END;

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

-- 3. 清理之前因不一致导致的错乱 FTS 数据
DELETE FROM agent_sessions_fts;
DELETE FROM agent_messages_fts;

-- 4. 使用正确的 rowid 重新索引现有数据
INSERT OR IGNORE INTO agent_sessions_fts(rowid, session_id, title, summary, metadata)
SELECT rowid, session_id, title, summary, metadata FROM agent_sessions;

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