"""rename restaurant to merchant

Revision ID: 96fe51a01bea
Revises: b79b129b318a
Create Date: 2026-07-21 14:03:58.805404

"""

from typing import Sequence, Union

from alembic import op

# revision identifiers, used by Alembic.
revision: str = "96fe51a01bea"
down_revision: Union[str, None] = "b79b129b318a"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Hand-written, not autogenerate's raw output: autogenerate saw the
    # Restaurant -> Merchant model/table rename as a drop-and-recreate of
    # `restaurants` (losing every row) plus a drop-and-add of
    # `branches.restaurant_id`, since it diffs schemas structurally and has
    # no notion of a rename. Replaced by hand with actual renames so
    # existing data survives. Also renaming the pkey/index/fk constraint
    # names that reference the old "restaurant(s)" name, so the schema
    # looks the same as if `merchants` had been created fresh.
    #
    # 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 (pre-existing
    # unique-index-vs-named-constraint drift unrelated to this migration).
    # Both removed by hand — same drift called out in 42828b3f2eea.
    op.rename_table("restaurants", "merchants")
    op.execute(
        "ALTER TABLE merchants RENAME CONSTRAINT restaurants_pkey TO merchants_pkey"
    )
    op.execute("ALTER INDEX ix_restaurants_owner_id RENAME TO ix_merchants_owner_id")
    op.execute(
        "ALTER TABLE merchants RENAME CONSTRAINT restaurants_owner_id_fkey "
        "TO merchants_owner_id_fkey"
    )

    op.alter_column("branches", "restaurant_id", new_column_name="merchant_id")
    op.execute(
        "ALTER INDEX ix_branches_restaurant_id RENAME TO ix_branches_merchant_id"
    )
    op.execute(
        "ALTER TABLE branches RENAME CONSTRAINT branches_restaurant_id_fkey "
        "TO branches_merchant_id_fkey"
    )


def downgrade() -> None:
    op.execute(
        "ALTER TABLE branches RENAME CONSTRAINT branches_merchant_id_fkey "
        "TO branches_restaurant_id_fkey"
    )
    op.execute(
        "ALTER INDEX ix_branches_merchant_id RENAME TO ix_branches_restaurant_id"
    )
    op.alter_column("branches", "merchant_id", new_column_name="restaurant_id")

    op.execute(
        "ALTER TABLE merchants RENAME CONSTRAINT merchants_owner_id_fkey "
        "TO restaurants_owner_id_fkey"
    )
    op.execute("ALTER INDEX ix_merchants_owner_id RENAME TO ix_restaurants_owner_id")
    op.execute(
        "ALTER TABLE merchants RENAME CONSTRAINT merchants_pkey TO restaurants_pkey"
    )
    op.rename_table("merchants", "restaurants")
