"""add user id card number

Revision ID: 029_user_id_card_no
Revises: 028_ticket_agent_departments
Create Date: 2026-06-14
"""

from alembic import op
import sqlalchemy as sa

revision = "029_user_id_card_no"
down_revision = "028_ticket_agent_departments"
branch_labels = None
depends_on = None


def _column_names(bind: sa.engine.Connection, table_name: str) -> set[str]:
    return {column["name"] for column in sa.inspect(bind).get_columns(table_name)}


def _index_names(bind: sa.engine.Connection, table_name: str) -> set[str]:
    return {index["name"] for index in sa.inspect(bind).get_indexes(table_name)}


def upgrade() -> None:
    bind = op.get_bind()
    tables = set(sa.inspect(bind).get_table_names())
    if "users" not in tables:
        return

    columns = _column_names(bind, "users")
    if "id_card_no" not in columns:
        op.add_column("users", sa.Column("id_card_no", sa.String(32), nullable=True))

    indexes = _index_names(bind, "users")
    if "ix_users_id_card_no" not in indexes:
        op.create_index("ix_users_id_card_no", "users", ["id_card_no"], unique=True)


def downgrade() -> None:
    bind = op.get_bind()
    tables = set(sa.inspect(bind).get_table_names())
    if "users" not in tables:
        return

    indexes = _index_names(bind, "users")
    if "ix_users_id_card_no" in indexes:
        op.drop_index("ix_users_id_card_no", table_name="users")

    columns = _column_names(bind, "users")
    if "id_card_no" in columns:
        op.drop_column("users", "id_card_no")
