-- 为 memory_atoms 表添加全文搜索索引，支持混合检索
CREATE EXTENSION IF NOT EXISTS vector;

ALTER TABLE memory_atoms ADD COLUMN IF NOT EXISTS content_tsv tsvector;

CREATE INDEX IF NOT EXISTS idx_memory_atoms_content_tsv
    ON memory_atoms USING GIN (content_tsv);

CREATE OR REPLACE FUNCTION update_memory_atoms_tsv() RETURNS trigger AS $$
BEGIN
    NEW.content_tsv := to_tsvector('simple', COALESCE(NEW.content, ''));
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_trigger WHERE tgname = 'trg_memory_atoms_tsv'
    ) THEN
        CREATE TRIGGER trg_memory_atoms_tsv
            BEFORE INSERT OR UPDATE ON memory_atoms
            FOR EACH ROW EXECUTE FUNCTION update_memory_atoms_tsv();
    END IF;
END $$;

UPDATE memory_atoms SET content_tsv = to_tsvector('simple', COALESCE(content, ''));