"""Merge the 'rewarded' advertisement placement into 'chat'.

Rewarded advertisements are shown exclusively in the chat "watch an ad to unlock
messages" flow, so the separate ``rewarded`` placement was redundant with the
existing ``chat`` placement (advertisement *type* already distinguishes rewarded
behaviour). This reverses migration ``f4a6c8b1d3e7`` and restores the approved
schema placement set ``ENUM('landing','marketplace','chat','sidebar')``.

Existing rewarded rows are migrated ``rewarded`` → ``chat`` before the MySQL ENUM
is narrowed, so administrators never recreate advertisements. The data UPDATE runs
on every dialect; the ENUM redefinition is MySQL-only (SQLite stores enums as
VARCHAR created fresh from metadata, so no column change is needed there).

Revision ID: a2c4e6f8b0d1
Revises: d8f0b2c4e6a9
Create Date: 2026-07-06

"""

from alembic import op

# revision identifiers, used by Alembic.
revision = "a2c4e6f8b0d1"
down_revision = "d8f0b2c4e6a9"
branch_labels = None
depends_on = None

_WITH_REWARDED = "ENUM('landing','marketplace','chat','sidebar','rewarded')"
_WITHOUT_REWARDED = "ENUM('landing','marketplace','chat','sidebar')"


def upgrade():
    bind = op.get_bind()
    # Move any rewarded-placement ads to the chat placement first so the value is
    # valid before the enum is narrowed (and to migrate SQLite/dev data too).
    op.execute("UPDATE advertisements SET placement='chat' WHERE placement='rewarded'")
    if bind.dialect.name == "mysql":
        op.execute(
            f"ALTER TABLE advertisements MODIFY COLUMN placement {_WITHOUT_REWARDED} NOT NULL"
        )


def downgrade():
    # Re-widen the enum so the 'rewarded' value is accepted again. The original
    # rewarded/chat split cannot be reconstructed (both are 'chat' now), so rows are
    # intentionally left as 'chat'; this only restores the column's accepted values.
    bind = op.get_bind()
    if bind.dialect.name == "mysql":
        op.execute(
            f"ALTER TABLE advertisements MODIFY COLUMN placement {_WITH_REWARDED} NOT NULL"
        )
