from decimal import Decimal
from typing import Optional, TYPE_CHECKING
from sqlalchemy import  String, Integer, Numeric,  SmallInteger, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from core.database import Base

from api.v1.modules.a76.general_catalogs.packages.models import Package

if TYPE_CHECKING:
    from ..models import LineItem
    
class LineQuantity(Base):
    """
    Quantity details for line items
    Consolidates all line-level data from Q and S tables
    """
    __tablename__ = "item_line_quantities"
    __table_args__ = {
        "schema": "a76",
    }
    
    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
    item_line_id: Mapped[int] = mapped_column(ForeignKey("a76.item_lines.id"))
    
    # Quantities
    quantity: Mapped[Optional[Decimal]] = mapped_column(Numeric(19, 8))  # CANTIMPO / CANTEXPO / CANTIMPODEF
    alternate_quantity: Mapped[Optional[Decimal]] = mapped_column(Numeric(19, 8))  # CANTALTERNA
    quantity_uma: Mapped[Optional[Decimal]] = mapped_column(Numeric(19, 8))  # CANTIMPOUMA / CANTEXPOUMA
    auxiliary_quantity: Mapped[Optional[Decimal]] = mapped_column(Numeric(19, 8))  # CANTIMPOAUXILIAR / CANTEXPOAUXILIAR
    
    # Quantities - Special (SCAF specific)
    quantity_temp_export: Mapped[Optional[Decimal]] = mapped_column(Numeric(19, 8))  # CANTEXPOTEMP
    serial_count: Mapped[Optional[int]] = mapped_column(Integer)  # CANT_SERIES/CANT_SERIESDEF
    
    # Weight
    net_weight: Mapped[Optional[Decimal]] = mapped_column(Numeric(19, 8))  # PESONETO
    gross_weight: Mapped[Optional[Decimal]] = mapped_column(Numeric(19, 8))  # PESOBRUTO    
    
    
    # Packaging
    package_id: Mapped[Optional[int]] = mapped_column(ForeignKey("a76.packages.id"))
    package_quantity: Mapped[Optional[int]] = mapped_column(Integer)  # CANTBULTOS
    container_quantity: Mapped[Optional[int]] = mapped_column(SmallInteger)  # CANTBULCONT
    container_description: Mapped[Optional[str]] = mapped_column(String(40))  # DESCCONTENEDOR
    box_count: Mapped[Optional[str]] = mapped_column(String(30))  # NOCAJAS
    
    # Relationship (one-to-one)
    line: Mapped["LineItem"] = relationship(back_populates="quantity")
    package_info: Mapped[Optional["Package"]] = relationship(Package)