# alembic/versions/ze4o5p6q7r8s9_rename_platform_admin_to_tenancy.py
"""Rename platform-admin module to tenancy.

Revision ID: ze4o5p6q7r8s9
Revises: zc2m3n4o5p6q7
Create Date: 2026-01-27 10:00:00.000000

"""

from alembic import op

# revision identifiers, used by Alembic.
revision = "ze4o5p6q7r8s9"
down_revision = "zc2m3n4o5p6q7"
branch_labels = None
depends_on = None


def upgrade() -> None:
    """Rename platform-admin to tenancy in platform_modules table."""
    # Update module_code in platform_modules junction table
    op.execute(
        """
        UPDATE platform_modules
        SET module_code = 'tenancy'
        WHERE module_code = 'platform-admin'
        """
    )

    # Also update any JSON settings that might reference the old module code
    # This handles Platform.settings["enabled_modules"] for legacy data
    # Note: settings column is JSON type, so we use text replacement approach
    op.execute(
        """
        UPDATE platforms
        SET settings = REPLACE(settings::text, '"platform-admin"', '"tenancy"')::json
        WHERE settings::text LIKE '%"platform-admin"%'
        """
    )


def downgrade() -> None:
    """Revert tenancy back to platform-admin."""
    # Revert module_code in platform_modules junction table
    op.execute(
        """
        UPDATE platform_modules
        SET module_code = 'platform-admin'
        WHERE module_code = 'tenancy'
        """
    )

    # Revert JSON settings
    op.execute(
        """
        UPDATE platforms
        SET settings = REPLACE(settings::text, '"tenancy"', '"platform-admin"')::json
        WHERE settings::text LIKE '%"tenancy"%'
        """
    )
