"""add advanced promo code rules

Revision ID: 047_promo_code_advanced_rules
Revises: 046_promo_code_discount_level
Create Date: 2026-06-19
"""

import sqlalchemy as sa
from alembic import op


revision = "047_promo_code_advanced_rules"
down_revision = "046_promo_code_discount_level"
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()
    columns = _columns(bind, "promo_codes")
    if "min_quantity" not in columns:
        op.add_column(
            "promo_codes",
            sa.Column("min_quantity", sa.Integer(), nullable=False, server_default=sa.text("0")),
        )
    if "max_discount_amount" not in columns:
        op.add_column(
            "promo_codes",
            sa.Column("max_discount_amount", sa.Integer(), nullable=False, server_default=sa.text("0")),
        )
    if "required_product_ids" not in columns:
        op.add_column("promo_codes", sa.Column("required_product_ids", sa.Text(), nullable=True))
    if "required_group_ids" not in columns:
        op.add_column("promo_codes", sa.Column("required_group_ids", sa.Text(), nullable=True))
    if "required_category_ids" not in columns:
        op.add_column("promo_codes", sa.Column("required_category_ids", sa.Text(), nullable=True))
    if "allowed_user_ids" not in columns:
        op.add_column("promo_codes", sa.Column("allowed_user_ids", sa.Text(), nullable=True))


def downgrade() -> None:
    bind = op.get_bind()
    columns = _columns(bind, "promo_codes")
    for column in [
        "allowed_user_ids",
        "required_category_ids",
        "required_group_ids",
        "required_product_ids",
        "max_discount_amount",
        "min_quantity",
    ]:
        if column in columns:
            op.drop_column("promo_codes", column)
