"""add full-text search vector to ai_sessions

Revision ID: dbf67047d4c8
Revises: 49150866ae44
Create Date: 2026-03-20 03:36:29.910843

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = 'dbf67047d4c8'
down_revision: Union[str, None] = '49150866ae44'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Add generated tsvector column for full-text search
    # Indexes: problem_summary, resolution_summary, escalation_reason, problem_domain
    op.execute("""
        ALTER TABLE ai_sessions ADD COLUMN IF NOT EXISTS search_vector tsvector
        GENERATED ALWAYS AS (
            to_tsvector('english',
                coalesce(problem_summary, '') || ' ' ||
                coalesce(resolution_summary, '') || ' ' ||
                coalesce(escalation_reason, '') || ' ' ||
                coalesce(problem_domain, ''))
        ) STORED
    """)
    # Add GIN index for fast FTS lookups
    op.execute("""
        CREATE INDEX IF NOT EXISTS idx_ai_sessions_search
        ON ai_sessions USING gin(search_vector)
    """)


def downgrade() -> None:
    op.execute("DROP INDEX IF EXISTS idx_ai_sessions_search")
    op.execute("ALTER TABLE ai_sessions DROP COLUMN IF EXISTS search_vector")
