"""Drop users.total_points, drop rewards/reward_redemptions and update transaction_type enum in point_transactions

Revision ID: 5101c3bd185a
Revises: b61c52e24249
Create Date: 2025-02-21 16:08:25.294712

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = '5101c3bd185a'
down_revision: Union[str, None] = 'b61c52e24249'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade():
    # 1. 임시로 point_transactions 테이블의 transaction_type 컬럼을
    #    기존 리스트에 'referral_bonus' 값을 추가하여 변경합니다.
    op.execute(
        "ALTER TABLE point_transactions MODIFY COLUMN transaction_type ENUM("
        "'step', 'referral', 'referral_bonus', 'redeem', 'admin_adjust', 'etc'"
        ") NOT NULL"
    )
    
    # 2. 기존에 저장된 'referral' 값을 'referral_bonus'로 업데이트합니다.
    op.execute(
        "UPDATE point_transactions SET transaction_type='referral_bonus' WHERE transaction_type='referral'"
    )
    
    # 3. 최종적으로 원하는 ENUM 목록으로 수정합니다.
    op.execute(
        "ALTER TABLE point_transactions MODIFY COLUMN transaction_type ENUM("
        "'step', 'achievement', 'referral_bonus', 'referral_chain', 'redeem', 'admin_adjust', 'etc'"
        ") NOT NULL"
    )
    
    # 4. rewards_redemptions 및 rewards 테이블 삭제
    op.drop_table('reward_redemptions')
    op.drop_table('rewards')


def downgrade():
    # 다운그레이드 시, ENUM 목록을 원래 상태로 복원합니다.
    op.execute(
        "ALTER TABLE point_transactions MODIFY COLUMN transaction_type ENUM("
        "'step', 'referral', 'redeem', 'admin_adjust', 'etc'"
        ") NOT NULL"
    )
    
    # 필요하다면 rewards, reward_redemptions 테이블을 재생성합니다.
    op.create_table(
        'rewards',
        sa.Column('id', sa.BigInteger(unsigned=True), primary_key=True, autoincrement=True),
        sa.Column('reward_name', sa.String(100), nullable=False),
        sa.Column('description', sa.Text, nullable=True),
        sa.Column('points_required', sa.Integer, nullable=False),
        sa.Column('country_code', sa.String(5), nullable=True),
        sa.Column('active', sa.Integer, nullable=False, server_default='1'),
        sa.Column('created_at', sa.DateTime, nullable=False, server_default=sa.func.now()),
        sa.Column('updated_at', sa.DateTime, nullable=False, server_default=sa.func.now(), onupdate=sa.func.now())
    )

    op.create_table(
        'reward_redemptions',
        sa.Column('id', sa.BigInteger(unsigned=True), primary_key=True, autoincrement=True),
        sa.Column('user_id', sa.BigInteger(unsigned=True), sa.ForeignKey('users.id', ondelete='CASCADE'), nullable=False),
        sa.Column('reward_id', sa.BigInteger(unsigned=True), sa.ForeignKey('rewards.id', ondelete='CASCADE'), nullable=False),
        sa.Column('points_spent', sa.Integer, nullable=False),
        sa.Column('created_at', sa.DateTime, nullable=False, server_default=sa.func.now())
    )