-- Full-text search on messages (v0.503 - CH1)
ALTER TABLE messages ADD COLUMN IF NOT EXISTS content_tsv tsvector;

CREATE INDEX IF NOT EXISTS idx_messages_content_fts
    ON messages USING GIN (content_tsv);

-- Trigger to auto-update tsvector on insert/update
CREATE OR REPLACE FUNCTION messages_content_tsv_trigger() RETURNS trigger AS $$
BEGIN
    NEW.content_tsv := to_tsvector('simple', COALESCE(NEW.content, ''));
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trg_messages_content_tsv ON messages;
CREATE TRIGGER trg_messages_content_tsv
    BEFORE INSERT OR UPDATE OF content ON messages
    FOR EACH ROW EXECUTE FUNCTION messages_content_tsv_trigger();

-- Backfill existing messages
UPDATE messages SET content_tsv = to_tsvector('simple', COALESCE(content, ''))
    WHERE content_tsv IS NULL;
