"""mall enhance: list_on_mall and mall item display fields

Revision ID: 055_mall_enhance
Revises: 9ec991d9bc55
Create Date: 2026-06-20
"""

import sqlalchemy as sa
from alembic import op


revision = "055_mall_enhance"
down_revision = "9ec991d9bc55"
branch_labels = None
depends_on = None


def _columns(bind, table_name: str) -> set[str]:
    return {column["name"] for column in sa.inspect(bind).get_columns(table_name)}


def upgrade() -> None:
    bind = op.get_bind()

    promo_columns = _columns(bind, "promo_codes")
    if "list_on_mall" not in promo_columns:
        op.add_column(
            "promo_codes",
            sa.Column("list_on_mall", sa.Boolean(), nullable=False, server_default=sa.text("0")),
        )

    mall_columns = _columns(bind, "coupon_mall_items")
    if "title" not in mall_columns:
        op.add_column("coupon_mall_items", sa.Column("title", sa.String(length=200), nullable=True))
    if "subtitle" not in mall_columns:
        op.add_column("coupon_mall_items", sa.Column("subtitle", sa.String(length=500), nullable=True))
    if "cover_image" not in mall_columns:
        op.add_column("coupon_mall_items", sa.Column("cover_image", sa.String(length=500), nullable=True))
    if "scope" not in mall_columns:
        op.add_column(
            "coupon_mall_items",
            sa.Column("scope", sa.String(length=32), nullable=False, server_default="public"),
        )
    if "visible_user_ids" not in mall_columns:
        op.add_column("coupon_mall_items", sa.Column("visible_user_ids", sa.Text(), nullable=True))
    if "sort_order" not in mall_columns:
        op.add_column(
            "coupon_mall_items",
            sa.Column("sort_order", sa.Integer(), nullable=False, server_default=sa.text("0")),
        )
    if "category" not in mall_columns:
        op.add_column("coupon_mall_items", sa.Column("category", sa.String(length=50), nullable=True))


def downgrade() -> None:
    bind = op.get_bind()

    mall_columns = _columns(bind, "coupon_mall_items")
    for col in ["category", "sort_order", "visible_user_ids", "scope", "cover_image", "subtitle", "title"]:
        if col in mall_columns:
            op.drop_column("coupon_mall_items", col)

    promo_columns = _columns(bind, "promo_codes")
    if "list_on_mall" in promo_columns:
        op.drop_column("promo_codes", "list_on_mall")
