"""
发货记录表模型 - 支持分包裹/分次发货功能
每次发货操作会生成一条记录，关联到 pending_shipments 表
"""

from datetime import datetime
from typing import Optional
from sqlalchemy import (
    Column, Integer, String, Text, DateTime, ForeignKey, Index
)
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.core.database import Base


class ShipmentRecord(Base):
    """发货记录表 - 记录每次发货的详细信息"""
    __tablename__ = "shipment_records"

    # 主键
    id = Column(Integer, primary_key=True, autoincrement=True)

    # 关联待发货订单
    pending_shipment_id = Column(
        Integer,
        ForeignKey('pending_shipments.id', ondelete='CASCADE'),
        nullable=False,
        comment='关联待发货订单ID'
    )

    # 关系
    pending_shipment = relationship("PendingShipment", back_populates="shipment_records")

    # 发货信息
    快递单号 = Column(String(100), nullable=False, comment='快递单号')
    快递公司 = Column(String(50), nullable=True, comment='快递公司名称')
    发货数量 = Column(Integer, nullable=False, default=1, comment='本次发货件数')
    发货时间 = Column(DateTime, nullable=True, comment='发货时间')

    # 操作信息
    操作员 = Column(String(50), nullable=True, comment='操作员')
    备注 = Column(Text, nullable=True, comment='备注信息')

    # 审计字段
    created_at = Column(DateTime, server_default=func.now(), comment='创建时间')

    # 表约束和索引
    __table_args__ = (
        Index('idx_shipment_records_pending', 'pending_shipment_id'),
        Index('idx_shipment_records_tracking', '快递单号'),
    )

    def __repr__(self):
        return f"<ShipmentRecord(id={self.id}, pending_shipment_id={self.pending_shipment_id}, 快递单号={self.快递单号})>"

    def to_dict(self):
        """Convert to dictionary for API responses"""
        return {
            'id': self.id,
            'pending_shipment_id': self.pending_shipment_id,
            '快递单号': self.快递单号,
            '快递公司': self.快递公司,
            '发货数量': self.发货数量,
            '发货时间': self.发货时间.isoformat() if self.发货时间 else None,
            '操作员': self.操作员,
            '备注': self.备注,
            'created_at': self.created_at.isoformat() if self.created_at else None,
        }
