"""Align Service Catalogue registration requirements with Registration Type master.

The Service Catalogue previously used a frontend-only legacy code "GST" while the
Registration Type master uses "GSTIN". Scope mapping compares these codes exactly.
This migration updates only the legacy Service Catalogue value and leaves service
IDs, service codes, firm selections, subscriptions, engagements, tasks and all
other catalogue data unchanged.
"""

from alembic import op
import sqlalchemy as sa


revision = "20260807_service_reg_master"
down_revision = "20260806_related_person_scope"
branch_labels = None
depends_on = None


def upgrade():
    bind = op.get_bind()
    inspector = sa.inspect(bind)

    if "service_catalogues" not in inspector.get_table_names():
        return

    columns = {column["name"] for column in inspector.get_columns("service_catalogues")}
    if "required_registration_type" not in columns:
        return

    bind.execute(
        sa.text(
            """
            UPDATE service_catalogues
               SET required_registration_type = 'GSTIN'
             WHERE UPPER(TRIM(required_registration_type)) = 'GST'
            """
        )
    )


def downgrade():
    # Deliberately do not restore GST. GSTIN is the canonical Registration Type
    # master code and reverting it would reintroduce the scope-map mismatch.
    pass
