from sqlalchemy import BigInteger, String, JSON, Integer, Index
from sqlalchemy.dialects.mysql import TINYINT
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.core.models.base import Base, TimestampMixin, TenantMixin


class ShippingCarrier(Base, TenantMixin, TimestampMixin):
    """快递公司主数据"""

    __tablename__ = "shipping_carriers"
    __table_args__ = (
        Index("ix_carrier_tenant_active", "tenant_id", "is_active"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    name: Mapped[str] = mapped_column(String(100), nullable=False, comment="快递公司名称，如 DHL Express")
    code: Mapped[str] = mapped_column(String(50), nullable=False, comment="唯一标识码，如 dhl / nz_post / fedex")
    logo_url: Mapped[str | None] = mapped_column(String(500), nullable=True, comment="Logo 图片 URL")
    tracking_url_template: Mapped[str | None] = mapped_column(
        String(500), nullable=True,
        comment="查件链接模板，用 {tracking_no} 占位，如 https://track.dhl.com/?ref={tracking_no}"
    )
    description: Mapped[str | None] = mapped_column(String(500), nullable=True, comment="描述/备注")
    api_config: Mapped[dict | None] = mapped_column(JSON, nullable=True, comment="API 密钥等敏感配置（加密存储）")
    sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment="显示排序")
    is_active: Mapped[int] = mapped_column(TINYINT(1), nullable=False, default=1, comment="是否启用")

    methods = relationship("ShippingMethod", back_populates="carrier_obj", lazy="noload")

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