from datetime import datetime
from typing import TYPE_CHECKING

from api.v1.common.base_models import TenantScopedMixin, TimestampMixin
from core.database import Base
from sqlalchemy import (
    DateTime,
    ForeignKeyConstraint,
    Integer,
    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 PedimentoRectificationOrigin(Base, TenantScopedMixin, TimestampMixin):
    __tablename__ = "pedimento_rectification_origin"
    __table_args__ = (
        PrimaryKeyConstraint("id", name="pedimento_rectification_origin_pkey"),        
        ForeignKeyConstraint(
            ["pedimento_id"],
            ["a76.pedimentos.id"],
            ondelete="CASCADE",
            name="fk_pedimento_rectification_origin",
        ),
        UniqueConstraint(
            "tenant_id",
            "company_id",
            "pedimento_id",
            name="pedimento_rectification_origin_pedimento_id_key",
        ),
        {"schema": "a76"},
    )

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

    original_pedimento_year: Mapped[str | None] = mapped_column(String(2), nullable=True)
    original_customs_office: Mapped[str | None] = mapped_column(String(3), nullable=True)
    original_license: Mapped[str | None] = mapped_column(String(4), nullable=True)
    original_pedimento_number: Mapped[str | None] = mapped_column(String(7), nullable=True)
    original_pedimento_code: Mapped[str | None] = mapped_column(String(2), nullable=True)
    original_payment_date: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    total_cash: Mapped[int | None] = mapped_column(Integer, nullable=True)
    total_others: Mapped[int | None] = mapped_column(Integer, nullable=True)
    reason: Mapped[str | None] = mapped_column(String(255), nullable=True)
    charge_to_client: Mapped[int | None] = mapped_column(SmallInteger, nullable=True)
    use_original_payment_date_for_interest_calc: Mapped[int | None] = mapped_column(
        SmallInteger, nullable=True
    )
    manual_calculation: Mapped[int | None] = mapped_column(SmallInteger, nullable=True)
    original_pedimento_norms: Mapped[int | None] = mapped_column(SmallInteger, nullable=True)

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