"""update advertisement logic

Revision ID: a31fb3c02c61
Revises: 5673962035f1
Create Date: 2025-02-24 08:47:28.610630

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = 'a31fb3c02c61'
down_revision: Union[str, None] = '5673962035f1'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # advertisements 테이블에서 더 이상 사용하지 않는 컬럼 제거
    with op.batch_alter_table("advertisements") as batch_op:
        batch_op.drop_column("ad_clicked")
        batch_op.drop_column("ad_click_time")
    
    # reward_redemptions 및 rewards 테이블 삭제
    op.drop_table('reward_redemptions')
    op.drop_table('rewards')


def downgrade() -> None:
    # downgrade 시에는 컬럼을 다시 생성합니다.
    with op.batch_alter_table("advertisements") as batch_op:
        batch_op.add_column(
            sa.Column(
                "ad_clicked",
                sa.Boolean(),
                nullable=False,
                server_default=sa.text("0")
            )
        )
        batch_op.add_column(
            sa.Column(
                "ad_click_time",
                sa.DateTime(),
                nullable=True
            )
        )
    
    # 필요하다면 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())
    )