from decimal import Decimal
from sqlalchemy import BigInteger, String, Integer, DECIMAL, UniqueConstraint, Index, ForeignKey
from sqlalchemy.dialects.mysql import TINYINT
from sqlalchemy.orm import Mapped, mapped_column
from app.core.models.base import Base, TimestampMixin, TenantMixin


class ProductUnitDict(Base, TenantMixin, TimestampMixin):
    """全局单位词典（每租户共享）"""

    __tablename__ = "product_unit_dict"
    __table_args__ = (
        UniqueConstraint("tenant_id", "unit_name", name="uk_unit_dict_tenant_name"),
        Index("ix_unit_dict_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)
    unit_name: Mapped[str] = mapped_column(String(50), nullable=False, comment="中文单位名，如'箱'")
    unit_name_en: Mapped[str | None] = mapped_column(String(50), nullable=True, default=None, comment="英文单位名，如'Box'")
    is_system: Mapped[int] = mapped_column(TINYINT(1), nullable=False, default=0, comment="1=内置词条不可删除")

    def __repr__(self) -> str:
        return f"<ProductUnitDict id={self.id} unit_name={self.unit_name!r}>"


class ProductSellingUnit(Base, TenantMixin, TimestampMixin):
    """商品销售单位配置"""

    __tablename__ = "product_selling_units"
    __table_args__ = (
        UniqueConstraint("tenant_id", "product_id", "unit_name", name="uk_selling_unit_product_name"),
        Index("ix_selling_unit_product", "product_id"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    product_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("products.id", ondelete="CASCADE"),
        nullable=False
    )
    dict_id: Mapped[int | None] = mapped_column(
        BigInteger, ForeignKey("product_unit_dict.id", ondelete="SET NULL"),
        nullable=True, comment="关联词典词条，自定义时为 NULL"
    )
    unit_name: Mapped[str] = mapped_column(String(50), nullable=False, comment="中文显示名")
    unit_name_en: Mapped[str | None] = mapped_column(String(50), nullable=True, default=None, comment="英文显示名")
    qty_per_base: Mapped[int] = mapped_column(Integer, nullable=False, default=1, comment="折算基础单位数量（个=1，箱=24）")
    is_base_unit: Mapped[int] = mapped_column(TINYINT(1), nullable=False, default=0, comment="1=基础最小单位")
    price_override: Mapped[Decimal | None] = mapped_column(
        DECIMAL(12, 2), nullable=True,
        comment="独立定价；NULL 时自动算 base_price × qty_per_base"
    )
    sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment="显示顺序")

    def __repr__(self) -> str:
        return f"<ProductSellingUnit id={self.id} product_id={self.product_id} unit_name={self.unit_name!r}>"
