from decimal import Decimal
from sqlalchemy import BigInteger, DECIMAL, Index, ForeignKey
from sqlalchemy.dialects.mysql import TINYINT
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.core.models.base import Base, TimestampMixin, TenantMixin


class ShippingRateTier(Base, TenantMixin, TimestampMixin):
    """运费阶梯明细（供 order_value_tier / weight_tier 计价方式使用）

    示例（按订单金额阶梯）：
      min_value=0,   max_value=50,   fee=10.00, is_free=0  → $0-50   收 $10
      min_value=50,  max_value=100,  fee=5.00,  is_free=0  → $50-100 收 $5
      min_value=100, max_value=None, fee=0,     is_free=1  → $100+   免运费
    """

    __tablename__ = "shipping_rate_tiers"
    __table_args__ = (
        Index("ix_tier_method_id", "method_id"),
        Index("ix_tier_tenant", "tenant_id"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    method_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("shipping_methods.id", ondelete="CASCADE"),
        nullable=False
    )
    min_value: Mapped[Decimal] = mapped_column(DECIMAL(12, 2), nullable=False, default=Decimal("0"),
                                               comment="区间下限（含）")
    max_value: Mapped[Decimal | None] = mapped_column(DECIMAL(12, 2), nullable=True,
                                                      comment="区间上限（不含），NULL=无上限")
    fee: Mapped[Decimal] = mapped_column(DECIMAL(10, 2), nullable=False, default=Decimal("0"),
                                         comment="该档运费")
    is_free: Mapped[int] = mapped_column(TINYINT(1), nullable=False, default=0, comment="1=该档免运费")
    sort_order: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)

    method = relationship("ShippingMethod", back_populates="tiers", lazy="noload")

    def __repr__(self) -> str:
        return f"<ShippingRateTier id={self.id} method_id={self.method_id} [{self.min_value}-{self.max_value}]>"
