"""mall limits: per-user claim limits and member level requirement

Revision ID: 056_mall_limits
Revises: 055_mall_enhance
Create Date: 2026-06-20
"""

import sqlalchemy as sa
from alembic import op


revision = "056_mall_limits"
down_revision = "055_mall_enhance"
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()
    mall_columns = _columns(bind, "coupon_mall_items")

    if "max_claims_per_user" not in mall_columns:
        op.add_column(
            "coupon_mall_items",
            sa.Column("max_claims_per_user", sa.Integer(), nullable=False, server_default=sa.text("1")),
        )
    if "max_claims_per_user_per_day" not in mall_columns:
        op.add_column(
            "coupon_mall_items",
            sa.Column("max_claims_per_user_per_day", sa.Integer(), nullable=False, server_default=sa.text("0")),
        )
    if "required_member_level" not in mall_columns:
        op.add_column(
            "coupon_mall_items",
            sa.Column("required_member_level", sa.Integer(), nullable=False, server_default=sa.text("0")),
        )
    if "required_member_level_name" not in mall_columns:
        op.add_column(
            "coupon_mall_items",
            sa.Column("required_member_level_name", sa.String(length=50), nullable=True),
        )
    if "is_hot" not in mall_columns:
        op.add_column(
            "coupon_mall_items",
            sa.Column("is_hot", sa.Boolean(), nullable=False, server_default=sa.text("0")),
        )


def downgrade() -> None:
    bind = op.get_bind()
    mall_columns = _columns(bind, "coupon_mall_items")
    for col in ["is_hot", "required_member_level_name", "required_member_level", "max_claims_per_user_per_day", "max_claims_per_user"]:
        if col in mall_columns:
            op.drop_column("coupon_mall_items", col)
