"""add user membership group fields

Revision ID: 030_user_membership_groups
Revises: 029_user_id_card_no
Create Date: 2026-06-14
"""

from alembic import op
import sqlalchemy as sa

revision = "030_user_membership_groups"
down_revision = "029_user_id_card_no"
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 "user_memberships" not in tables:
        return

    columns = _column_names(bind, "user_memberships")
    if "member_level_locked" not in columns:
        op.add_column(
            "user_memberships",
            sa.Column("member_level_locked", sa.Boolean(), nullable=False, server_default=sa.text("0")),
        )
        op.alter_column("user_memberships", "member_level_locked", server_default=None)
    if "agent_tier" not in columns:
        op.add_column("user_memberships", sa.Column("agent_tier", sa.String(32), nullable=True))

    indexes = _index_names(bind, "user_memberships")
    if "ix_user_memberships_agent_tier" not in indexes:
        op.create_index("ix_user_memberships_agent_tier", "user_memberships", ["agent_tier"])


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

    indexes = _index_names(bind, "user_memberships")
    if "ix_user_memberships_agent_tier" in indexes:
        op.drop_index("ix_user_memberships_agent_tier", table_name="user_memberships")

    columns = _column_names(bind, "user_memberships")
    if "agent_tier" in columns:
        op.drop_column("user_memberships", "agent_tier")
    if "member_level_locked" in columns:
        op.drop_column("user_memberships", "member_level_locked")
