"""add branch scoping to promo codes

Revision ID: 4455bf565acf
Revises: 39b310f489be
Create Date: 2026-07-22 09:09:29.293940

"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = "4455bf565acf"
down_revision: Union[str, None] = "39b310f489be"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # NOTE: autogenerate also proposed op.drop_table('spatial_ref_sys')
    # (a PostGIS system table — dropping it would break PostGIS
    # entirely) and dropping refresh_tokens_token_hash_key (recurring,
    # pre-existing unique-index-vs-named-constraint drift unrelated to
    # this migration — same drift called out in 42828b3f2eea). Both
    # removed by hand. The branch_id -> branches foreign key is named
    # explicitly (autogenerate left it anonymous), since an anonymous
    # constraint can't be dropped by name in downgrade().
    op.add_column("promo_codes", sa.Column("branch_id", sa.Uuid(), nullable=True))
    op.create_index(
        op.f("ix_promo_codes_branch_id"), "promo_codes", ["branch_id"], unique=False
    )
    op.create_foreign_key(
        "fk_promo_codes_branch_id_branches",
        "promo_codes",
        "branches",
        ["branch_id"],
        ["id"],
        ondelete="CASCADE",
    )


def downgrade() -> None:
    op.drop_constraint(
        "fk_promo_codes_branch_id_branches", "promo_codes", type_="foreignkey"
    )
    op.drop_index(op.f("ix_promo_codes_branch_id"), table_name="promo_codes")
    op.drop_column("promo_codes", "branch_id")
