from decimal import Decimal
from typing import TYPE_CHECKING, Optional

from api.v1.common.base_models import TenantScopedMixin, TimestampMixin
from core.database import Base
from sqlalchemy import (
    ForeignKeyConstraint,
    Integer,
    Numeric,
    PrimaryKeyConstraint,
    SmallInteger,
    String,
    UniqueConstraint,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship

if TYPE_CHECKING:
    from api.v1.modules.a76.pedmientos.models.pedimentos import Pedimentos


class PedimentoDecrementables(Base, TenantScopedMixin, TimestampMixin):
    __tablename__ = "pedimento_decrementables"
    __table_args__ = (
        PrimaryKeyConstraint("id", name="pedimento_decrementables_pkey"),
        ForeignKeyConstraint(
            ["pedimento_id"],
            ["a76.pedimentos.id"],
            ondelete="CASCADE",
            name="fk_pedimento_decrementables",
        ),
        UniqueConstraint(
            "tenant_id",
            "company_id",
            "pedimento_id",
            name="pedimento_decrementables_pedimento_id_key",
        ),
        {"schema": "a76"},
    )

    id: Mapped[int] = mapped_column(Integer)
    pedimento_id: Mapped[int] = mapped_column(Integer, nullable=False)

    freight: Mapped[Optional[Decimal]] = mapped_column(Numeric(13, 2))
    insurance: Mapped[Optional[Decimal]] = mapped_column(Numeric(13, 2))
    loading: Mapped[Optional[Decimal]] = mapped_column(Numeric(13, 2))
    unloading: Mapped[Optional[Decimal]] = mapped_column(Numeric(13, 2))
    others: Mapped[Optional[Decimal]] = mapped_column(Numeric(13, 2))
    currency: Mapped[Optional[str]] = mapped_column(String(3))
    currency_factor: Mapped[Optional[Decimal]] = mapped_column(Numeric(15, 8))
    not_affect_usd_value: Mapped[Optional[int]] = mapped_column(SmallInteger)
    not_affect_customs_value: Mapped[Optional[int]] = mapped_column(SmallInteger)

    pedimento: Mapped["Pedimentos"] = relationship(
        "Pedimentos", back_populates="pedimento_decrementables"
    )
