"""migrate field type from enum to string to support custom taxonomies

Revision ID: 795f46f656c0
Revises: 303287c70600
Create Date: 2025-11-18 18:30:00.000000

"""

import sqlalchemy as sa
from alembic import op
from loguru import logger

# revision identifiers, used by Alembic.
revision = "795f46f656c0"
down_revision = "303287c70600"
branch_labels = None
depends_on = None

# Original enum values used by AllowedTypes
ALLOWED_TYPES = (
    "string",
    "string[]",
)

# Name for the PostgreSQL enum type that backs AllowedTypes
PG_ENUM_NAME = "allowedtypes"


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    # Alter field_type column from Enum -> String
    # Use a PostgreSQL USING clause to safely cast enum -> text
    op.alter_column(
        "plus_custom_field_definition",
        "field_type",
        existing_type=sa.Enum(*ALLOWED_TYPES, name=PG_ENUM_NAME),
        type_=sa.String(),
        postgresql_using="field_type::text",
        nullable=False,
    )

    # Data migration: Convert old enum value 'string_list' to 'string[]'
    op.execute(
        """
        UPDATE plus_custom_field_definition
        SET field_type = 'string[]'
        WHERE field_type = 'string_list'
        """
    )

    # Drop the unused enum type after the column has been converted
    op.execute(f'DROP TYPE IF EXISTS "{PG_ENUM_NAME}"')
    # ### end Alembic commands ###


def downgrade():
    """
    This migration does not support downgrades.
    Converting string back to enum would fail if taxonomy keys are present.
    """
    logger.info("Conversion of str to enum AllowedTypes is unsupported.")
