"""add referral_reward point type

Revision ID: 032_referral_reward_point_type
Revises: 031_agent_system
Create Date: 2026-06-16
"""
from alembic import op


revision = "032_referral_reward_point_type"
down_revision = "031_agent_system"
branch_labels = None
depends_on = None


POINT_TYPES = (
    "order_reward",
    "order_refund",
    "points_use",
    "points_refund",
    "admin_adjust",
    "activity_gift",
    "agent_profit",
    "agent_subsidy",
    "referral_reward",
)


OLD_POINT_TYPES = (
    "order_reward",
    "order_refund",
    "points_use",
    "points_refund",
    "admin_adjust",
    "activity_gift",
    "agent_profit",
    "agent_subsidy",
    "member_commission",
)


def _enum_sql(values: tuple[str, ...]) -> str:
    return ",".join(f"'{value}'" for value in values)


def upgrade() -> None:
    bind = op.get_bind()
    if bind.dialect.name == "mysql":
        transitional = tuple(dict.fromkeys((*OLD_POINT_TYPES, *POINT_TYPES)))
        op.execute(
            f"ALTER TABLE point_logs MODIFY change_type ENUM({_enum_sql(transitional)}) NOT NULL"
        )
        op.execute("UPDATE point_logs SET change_type = 'referral_reward' WHERE change_type = 'member_commission'")
        op.execute(
            f"ALTER TABLE point_logs MODIFY change_type ENUM({_enum_sql(POINT_TYPES)}) NOT NULL"
        )


def downgrade() -> None:
    bind = op.get_bind()
    if bind.dialect.name == "mysql":
        op.execute("UPDATE point_logs SET change_type = 'activity_gift' WHERE change_type = 'referral_reward'")
        op.execute(
            f"ALTER TABLE point_logs MODIFY change_type ENUM({_enum_sql(OLD_POINT_TYPES)}) NOT NULL"
        )
