"""Rename legacy account_tier column to tier when tier is missing

Some SQLite databases were stamped at head but still use account_tier from an
older branch; the ORM expects column name tier (migration 002).

Revision ID: 004_rename_account_tier
Revises: 5206607942a2
Create Date: 2026-04-13

"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = "004_rename_account_tier"
down_revision: Union[str, None] = "5206607942a2"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    conn = op.get_bind()
    insp = sa.inspect(conn)
    cols = {c["name"] for c in insp.get_columns("users")}
    if "account_tier" in cols and "tier" not in cols:
        op.alter_column(
            "users",
            "account_tier",
            new_column_name="tier",
            existing_type=sa.String(10),
            existing_nullable=True,
        )


def downgrade() -> None:
    conn = op.get_bind()
    insp = sa.inspect(conn)
    cols = {c["name"] for c in insp.get_columns("users")}
    if "tier" in cols and "account_tier" not in cols:
        op.alter_column(
            "users",
            "tier",
            new_column_name="account_tier",
            existing_type=sa.String(10),
            existing_nullable=True,
        )
