from typing import TYPE_CHECKING, Optional

from core.database import Base
from sqlalchemy import ForeignKeyConstraint, Integer, PrimaryKeyConstraint, String
from sqlalchemy.orm import Mapped, mapped_column, relationship

if TYPE_CHECKING:
    from ..pedimento_codes.models import PedimentoCode
    from ..pedimento_regimens.models import RegimenPedimento


class CodePedimentoRegimen(Base):
    __tablename__ = "code_pedimento_regimens"  # GClavePedRegimen
    __table_args__ = (
        ForeignKeyConstraint(
            ["pedimento_code"], ["public.pedimento_codes.code"], name="fk_codeped"
        ),
        ForeignKeyConstraint(
            ["regimen_code"], ["public.pedimento_regimens.code"], name="fk_regimenped"
        ),
        PrimaryKeyConstraint("id", name="clave_pedimento_regimens_pkey"),
        {"schema": "public", "extend_existing": True},
    )

    id: Mapped[int] = mapped_column(Integer)
    pedimento_code: Mapped[str] = mapped_column(String(3), nullable=False)
    regimen_code: Mapped[Optional[str]] = mapped_column(
        String(3), nullable=False)
    type_code: Mapped[Optional[str]] = mapped_column(
        String(1)
    )  # si aplica un tipo de relación

    # Relaciones ORM
    # GClavePed
    pedimento: Mapped["PedimentoCode"] = relationship(
        "PedimentoCode", back_populates="regimens"
    )
    # GRegimenPed
    regimen: Mapped[Optional["RegimenPedimento"]] = relationship(
        "RegimenPedimento", back_populates="claves_pedimento"
    )

    def __repr__(self):
        return f"<ClavePedimentoRegimen(pedimento={self.pedimento_code}, regimen={self.regimen_code}, type={self.type_code})>"
