"""Phase 12.1 — Digital Menu Catalog schema."""
from alembic import op
import sqlalchemy as sa
from app.core.database import Base
import app.models  # noqa: F401

revision = "0002_phase_121_menu_catalog"
down_revision = "0001_initial"
branch_labels = None
depends_on = None


def upgrade():
    bind = op.get_bind()
    columns = {c["name"] for c in sa.inspect(bind).get_columns("menu_items")}
    with op.batch_alter_table("menu_items") as batch:
        if "preparation_minutes" not in columns:
            batch.add_column(sa.Column("preparation_minutes", sa.Integer(), nullable=True))
        if "calories" not in columns:
            batch.add_column(sa.Column("calories", sa.Integer(), nullable=True))
        if "spicy_level" not in columns:
            batch.add_column(
                sa.Column("spicy_level", sa.Integer(), nullable=False, server_default="0")
            )
        if "is_vegetarian" not in columns:
            batch.add_column(
                sa.Column("is_vegetarian", sa.Boolean(), nullable=False, server_default=sa.false())
            )
        if "is_vegan" not in columns:
            batch.add_column(
                sa.Column("is_vegan", sa.Boolean(), nullable=False, server_default=sa.false())
            )
        if "is_gluten_free" not in columns:
            batch.add_column(
                sa.Column("is_gluten_free", sa.Boolean(), nullable=False, server_default=sa.false())
            )
        if "tags" not in columns:
            batch.add_column(sa.Column("tags", sa.JSON(), nullable=True))
        if "primary_media_ref" not in columns:
            batch.add_column(sa.Column("primary_media_ref", sa.String(255), nullable=True))

    # Create new catalog tables from metadata (additive)
    Base.metadata.create_all(bind=bind)


def downgrade():
    bind = op.get_bind()
    for table in (
        "menu_localizations",
        "menu_media_refs",
        "availability_windows",
        "menu_item_allergens",
        "menu_item_modifiers",
        "modifier_options",
        "modifier_groups",
        "allergens",
    ):
        if sa.inspect(bind).has_table(table):
            op.drop_table(table)

    columns = {c["name"] for c in sa.inspect(bind).get_columns("menu_items")}
    with op.batch_alter_table("menu_items") as batch:
        for col in (
            "primary_media_ref",
            "tags",
            "is_gluten_free",
            "is_vegan",
            "is_vegetarian",
            "spicy_level",
            "calories",
            "preparation_minutes",
        ):
            if col in columns:
                batch.drop_column(col)
