"""restructure restaurants into restaurant-branch model

Revision ID: 03ef5de3db2e
Revises: ac8c909ec503
Create Date: 2026-07-14 16:28:21.870254

"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision: str = "03ef5de3db2e"
down_revision: Union[str, None] = "ac8c909ec503"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Needed for the distance-sort query in
    # app.api.v1.endpoints.restaurants.list_branches (ST_Distance /
    # ST_MakePoint). Branch itself still stores plain lat/lng floats —
    # see app.models.branch for why there's no stored geography column.
    op.execute("CREATE EXTENSION IF NOT EXISTS postgis")

    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "branches",
        sa.Column("id", sa.Uuid(), nullable=False),
        sa.Column("restaurant_id", sa.Uuid(), nullable=False),
        sa.Column("name", sa.String(length=150), nullable=False),
        sa.Column("address", sa.String(length=255), nullable=False),
        sa.Column("latitude", sa.Float(), nullable=False),
        sa.Column("longitude", sa.Float(), nullable=False),
        sa.Column("phone", sa.String(length=20), nullable=False),
        sa.Column("cover_image_url", sa.String(length=500), nullable=True),
        sa.Column("approval_status", sa.String(length=20), nullable=False),
        sa.Column("is_active", sa.Boolean(), nullable=False),
        sa.Column(
            "created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False
        ),
        sa.Column(
            "updated_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False
        ),
        sa.Column("deleted_at", sa.DateTime(), nullable=True),
        sa.ForeignKeyConstraint(
            ["restaurant_id"], ["restaurants.id"], ondelete="CASCADE"
        ),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(
        op.f("ix_branches_restaurant_id"), "branches", ["restaurant_id"], unique=False
    )
    op.create_table(
        "branch_managers",
        sa.Column("id", sa.Uuid(), nullable=False),
        sa.Column("branch_id", sa.Uuid(), nullable=False),
        sa.Column("user_id", sa.Uuid(), nullable=False),
        sa.Column(
            "created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False
        ),
        sa.ForeignKeyConstraint(["branch_id"], ["branches.id"], ondelete="CASCADE"),
        sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("user_id"),
    )
    op.create_index(
        op.f("ix_branch_managers_branch_id"),
        "branch_managers",
        ["branch_id"],
        unique=False,
    )
    op.add_column("menu_categories", sa.Column("branch_id", sa.Uuid(), nullable=False))
    op.drop_index("ix_menu_categories_restaurant_id", table_name="menu_categories")
    op.create_index(
        op.f("ix_menu_categories_branch_id"),
        "menu_categories",
        ["branch_id"],
        unique=False,
    )
    op.drop_constraint(
        "menu_categories_restaurant_id_fkey", "menu_categories", type_="foreignkey"
    )
    op.create_foreign_key(
        None, "menu_categories", "branches", ["branch_id"], ["id"], ondelete="CASCADE"
    )
    op.drop_column("menu_categories", "restaurant_id")
    op.add_column("menu_items", sa.Column("branch_id", sa.Uuid(), nullable=False))
    op.add_column(
        "menu_items",
        sa.Column(
            "dietary_info",
            sa.JSON().with_variant(
                postgresql.JSONB(astext_type=sa.Text()), "postgresql"
            ),
            nullable=False,
        ),
    )
    op.drop_index("ix_menu_items_restaurant_id", table_name="menu_items")
    op.create_index(
        op.f("ix_menu_items_branch_id"), "menu_items", ["branch_id"], unique=False
    )
    op.drop_constraint(
        "menu_items_restaurant_id_fkey", "menu_items", type_="foreignkey"
    )
    op.create_foreign_key(
        None, "menu_items", "branches", ["branch_id"], ["id"], ondelete="CASCADE"
    )
    op.drop_column("menu_items", "restaurant_id")
    # NOTE: autogenerate also proposed dropping refresh_tokens_token_hash_key
    # and users_phone_key here — pre-existing drift (unique index vs named
    # unique constraint) unrelated to this migration, left alone on purpose.
    op.add_column(
        "restaurants", sa.Column("logo_url", sa.String(length=500), nullable=True)
    )
    op.drop_index("ix_restaurants_owner_id", table_name="restaurants")
    op.create_index(
        op.f("ix_restaurants_owner_id"), "restaurants", ["owner_id"], unique=False
    )
    op.drop_column("restaurants", "approval_status")
    op.drop_column("restaurants", "address")
    op.drop_column("restaurants", "image_url")
    op.drop_column("restaurants", "is_active")
    op.drop_column("restaurants", "phone")
    op.drop_column("restaurants", "longitude")
    op.drop_column("restaurants", "latitude")
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "restaurants",
        sa.Column(
            "latitude",
            sa.DOUBLE_PRECISION(precision=53),
            autoincrement=False,
            nullable=True,
        ),
    )
    op.add_column(
        "restaurants",
        sa.Column(
            "longitude",
            sa.DOUBLE_PRECISION(precision=53),
            autoincrement=False,
            nullable=True,
        ),
    )
    op.add_column(
        "restaurants",
        sa.Column("phone", sa.VARCHAR(length=20), autoincrement=False, nullable=False),
    )
    op.add_column(
        "restaurants",
        sa.Column("is_active", sa.BOOLEAN(), autoincrement=False, nullable=False),
    )
    op.add_column(
        "restaurants",
        sa.Column(
            "image_url", sa.VARCHAR(length=500), autoincrement=False, nullable=True
        ),
    )
    op.add_column(
        "restaurants",
        sa.Column(
            "address", sa.VARCHAR(length=255), autoincrement=False, nullable=False
        ),
    )
    op.add_column(
        "restaurants",
        sa.Column(
            "approval_status",
            sa.VARCHAR(length=20),
            autoincrement=False,
            nullable=False,
        ),
    )
    op.drop_index(op.f("ix_restaurants_owner_id"), table_name="restaurants")
    op.create_index("ix_restaurants_owner_id", "restaurants", ["owner_id"], unique=True)
    op.drop_column("restaurants", "logo_url")
    op.add_column(
        "menu_items",
        sa.Column("restaurant_id", sa.UUID(), autoincrement=False, nullable=False),
    )
    op.drop_constraint(None, "menu_items", type_="foreignkey")
    op.create_foreign_key(
        "menu_items_restaurant_id_fkey",
        "menu_items",
        "restaurants",
        ["restaurant_id"],
        ["id"],
        ondelete="CASCADE",
    )
    op.drop_index(op.f("ix_menu_items_branch_id"), table_name="menu_items")
    op.create_index(
        "ix_menu_items_restaurant_id", "menu_items", ["restaurant_id"], unique=False
    )
    op.drop_column("menu_items", "dietary_info")
    op.drop_column("menu_items", "branch_id")
    op.add_column(
        "menu_categories",
        sa.Column("restaurant_id", sa.UUID(), autoincrement=False, nullable=False),
    )
    op.drop_constraint(None, "menu_categories", type_="foreignkey")
    op.create_foreign_key(
        "menu_categories_restaurant_id_fkey",
        "menu_categories",
        "restaurants",
        ["restaurant_id"],
        ["id"],
        ondelete="CASCADE",
    )
    op.drop_index(op.f("ix_menu_categories_branch_id"), table_name="menu_categories")
    op.create_index(
        "ix_menu_categories_restaurant_id",
        "menu_categories",
        ["restaurant_id"],
        unique=False,
    )
    op.drop_column("menu_categories", "branch_id")
    op.drop_index(op.f("ix_branch_managers_branch_id"), table_name="branch_managers")
    op.drop_table("branch_managers")
    op.drop_index(op.f("ix_branches_restaurant_id"), table_name="branches")
    op.drop_table("branches")
    # ### end Alembic commands ###
