ALTER TABLE rag_conversation
    ADD COLUMN IF NOT EXISTS title_source VARCHAR(20) NOT NULL DEFAULT 'default',
    ADD COLUMN IF NOT EXISTS title_generation_status VARCHAR(20) NOT NULL DEFAULT 'idle',
    ADD COLUMN IF NOT EXISTS title_generated_at TIMESTAMPTZ,
    ADD COLUMN IF NOT EXISTS first_question_message_id VARCHAR(100),
    ADD COLUMN IF NOT EXISTS first_answer_message_id VARCHAR(100),
    ADD COLUMN IF NOT EXISTS title_generation_error TEXT,
    ADD COLUMN IF NOT EXISTS last_message_at TIMESTAMPTZ;

UPDATE rag_conversation
SET title_source = 'default'
WHERE title_source IS NULL OR BTRIM(title_source) = '';

UPDATE rag_conversation
SET title_generation_status = 'idle'
WHERE title_generation_status IS NULL OR BTRIM(title_generation_status) = '';

CREATE INDEX IF NOT EXISTS idx_rag_conversation_title_generation_status
ON rag_conversation(title_generation_status)
WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_rag_conversation_last_message_at
ON rag_conversation(last_message_at DESC)
WHERE deleted_at IS NULL;
