from decimal import Decimal
from sqlalchemy import BigInteger, Integer, DECIMAL, Index, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column
from app.core.models.base import Base, TenantMixin


class DiscountTier(Base, TenantMixin):
    """阶梯折扣配置

    每行对应一个阶梯门槛，同一 discount_id 下可有多行。
    引擎按 sort_order 升序取最高满足档。

    示例（满额阶梯）：
        sort_order=1  min_amount=100  discount_value=10
        sort_order=2  min_amount=200  discount_value=20
        sort_order=3  min_amount=500  discount_value=50

    示例（满件阶梯）：
        sort_order=1  min_qty=3  discount_value=5
        sort_order=2  min_qty=6  discount_value=12
    """

    __tablename__ = "discount_tiers"
    __table_args__ = (
        Index("ix_tier_discount_id", "discount_id"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    discount_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("discounts.id", ondelete="CASCADE"), nullable=False
    )
    sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment="排序，升序")
    min_amount: Mapped[Decimal | None] = mapped_column(DECIMAL(12, 2), nullable=True, comment="门槛金额")
    min_qty: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="门槛件数")
    discount_value: Mapped[Decimal] = mapped_column(DECIMAL(10, 2), nullable=False, comment="该档折扣值（金额或百分比）")

    def __repr__(self) -> str:
        return f"<DiscountTier discount_id={self.discount_id} sort={self.sort_order} value={self.discount_value}>"
