"""物流轨迹日志模型"""
from datetime import datetime
from sqlalchemy import BigInteger, String, JSON, DateTime, Index, ForeignKey
from sqlalchemy.dialects.mysql import DATETIME as MYSQL_DATETIME
from sqlalchemy.orm import Mapped, mapped_column
from app.core.models.base import Base, TimestampMixin


class OrderDeliveryLog(Base, TimestampMixin):
    """物流轨迹日志"""

    __tablename__ = "order_delivery_logs"
    __table_args__ = (
        Index("ix_delivery_order", "order_id"),
        Index("ix_delivery_tenant", "tenant_id"),
        Index("ix_delivery_order_no", "order_no"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    order_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("orders.id", ondelete="CASCADE"), nullable=False
    )
    order_no: Mapped[str] = mapped_column(String(50), nullable=False, index=True)
    tenant_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("tenants.id", ondelete="RESTRICT"),
        nullable=False, index=True
    )
    carrier: Mapped[str] = mapped_column(String(50), nullable=False, comment="快递公司名称")
    tracking_no: Mapped[str] = mapped_column(String(100), nullable=False, comment="运单号")
    status: Mapped[str] = mapped_column(
        String(30), nullable=False, server_default="PENDING",
        comment="PENDING/PICKED_UP/IN_TRANSIT/DELIVERED/EXCEPTION/RETURNED"
    )
    location: Mapped[str | None] = mapped_column(String(200), nullable=True)
    description: Mapped[str | None] = mapped_column(String(500), nullable=True)
    event_time: Mapped[datetime | None] = mapped_column(MYSQL_DATETIME(fsp=3), nullable=True)
    raw_response: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    def __repr__(self) -> str:
        return f"<OrderDeliveryLog order_no={self.order_no!r} status={self.status!r}>"