"""Rename rematch event type to game_choice

Revision ID: 008_rename_to_game_choice
Revises: 007_add_event_assignment_fields
Create Date: 2024-12-15

"""
from alembic import op


# revision identifiers, used by Alembic.
revision = "008_rename_to_game_choice"
down_revision = "007_add_event_assignment_fields"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Update event type from 'rematch' to 'game_choice' in events table
    # These UPDATE statements are idempotent - safe to run multiple times
    op.execute("UPDATE events SET type = 'game_choice' WHERE type = 'rematch'")

    # Update event_type in assignments table
    op.execute("UPDATE assignments SET event_type = 'game_choice' WHERE event_type = 'rematch'")

    # Update activity data that references rematch event
    # Cast JSON to JSONB, apply jsonb_set, then cast back to JSON
    op.execute("""
        UPDATE activities
        SET data = jsonb_set(data::jsonb, '{event_type}', '"game_choice"')::json
        WHERE data->>'event_type' = 'rematch'
    """)


def downgrade() -> None:
    # Revert event type from 'game_choice' to 'rematch'
    op.execute("UPDATE events SET type = 'rematch' WHERE type = 'game_choice'")
    op.execute("UPDATE assignments SET event_type = 'rematch' WHERE event_type = 'game_choice'")
    op.execute("""
        UPDATE activities
        SET data = jsonb_set(data::jsonb, '{event_type}', '"rematch"')::json
        WHERE data->>'event_type' = 'game_choice'
    """)
