from typing import Optional, TYPE_CHECKING
from sqlalchemy import Integer, String, UniqueConstraint, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from api.v1.common.base_models import TenantScopedMixin, TimestampMixin
from core.database import Base


if TYPE_CHECKING:
    from api.v1.modules.a76.items.models import LineItem

class Identifier(Base, TenantScopedMixin, TimestampMixin):
    __tablename__ = "identifiers"
    __table_args__ = (
        UniqueConstraint("code", name="uq_identifier_code"),
        {"schema": "a76"}
    )

    id: Mapped[int] = mapped_column(
        Integer, primary_key=True, autoincrement=True)

    code: Mapped[str] = mapped_column(String(2), nullable=False)  # CLAVE

    description: Mapped[Optional[str]] = mapped_column(
        String(1000), nullable=True)  # DESCRIPCION

    level: Mapped[Optional[str]] = mapped_column(
        String(1), nullable=True)  # NIVEL
        
    complement: Mapped[Optional[str]] = mapped_column(
        String(5000), nullable=True)  # COMPLEMENTO

    details: Mapped[list["IdentifierDetail"]] = relationship(
        back_populates="identifier")


class IdentifierDetail(Base, TenantScopedMixin, TimestampMixin):
    __tablename__ = "identifier_details"
    __table_args__ = (
        {"schema": "a76"}
    )

    id: Mapped[int] = mapped_column(
        Integer, primary_key=True, autoincrement=True)
    invoice_consecutive: Mapped[Optional[int]] = mapped_column(
        Integer, nullable=True)  # CONSECUTIVOFACTURA
    part_line: Mapped[Optional[int]] = mapped_column(
        Integer, nullable=True)  # LINEAPARTIDA
    identifier_code: Mapped[Optional[str]] = mapped_column(
        String(2), ForeignKey("a76.identifiers.code"), nullable=True)  # ID
    item_line_id: Mapped[Optional[int]] = mapped_column(
        ForeignKey("a76.item_lines.id"), nullable=True)
    module: Mapped[Optional[str]] = mapped_column(
        String(20), nullable=True)  # MODULO
    complement1: Mapped[Optional[str]] = mapped_column(
        String(50), nullable=True)  # COMPLEMENTO1
    complement2: Mapped[Optional[str]] = mapped_column(
        String(51), nullable=True)  # COMPLEMENTO2
    complement3: Mapped[Optional[str]] = mapped_column(
        String(50), nullable=True)  # COMPLEMENTO3

    identifier: Mapped["Identifier"] = relationship(back_populates="details")
    line: Mapped[Optional["LineItem"]] = relationship(back_populates="identifiers")
