"""add question insight message index

Revision ID: 0013_question_insight_indexes
Revises: 0012_knowledge_latest_only
"""

from alembic import op
import sqlalchemy as sa


revision = "0013_question_insight_indexes"
down_revision = "0012_knowledge_latest_only"
branch_labels = None
depends_on = None


def upgrade() -> None:
    _create_index_if_missing("sys_chat_message", "ix_chat_message_role_created", ["role", "created_at"])


def downgrade() -> None:
    indexes = {item["name"] for item in sa.inspect(op.get_bind()).get_indexes("sys_chat_message")}
    if "ix_chat_message_role_created" in indexes:
        op.drop_index("ix_chat_message_role_created", table_name="sys_chat_message")


def _create_index_if_missing(table: str, name: str, columns: list[str]) -> None:
    if name not in {item["name"] for item in sa.inspect(op.get_bind()).get_indexes(table)}:
        op.create_index(name, table, columns)
