"""
Modelos ORM para gestión de catálogos de errores
"""

from typing import Optional

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


class ErrorClassification(Base, TenantScopedMixin, TimestampMixin):
    """
    Modelo para la tabla ErrorClassification - Clasificación de Errores
    """

    __tablename__ = "error_classifications"  # GCatErroresClas
    __table_args__ = (
        PrimaryKeyConstraint("id", name="error_classifications_pkey"),
        UniqueConstraint("code", name="error_classifications_code_unique"),
        {"schema": "a76"},
    )

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

    # Classification code (unique)
    code: Mapped[str] = mapped_column(String(100), nullable=False, unique=True)

    # Classification information
    level: Mapped[Optional[str]] = mapped_column(String(3))

    # Relationships
    errors: Mapped[list["ErrorCatalog"]] = relationship(
        "ErrorCatalog", back_populates="classification", cascade="all, delete-orphan"
    )

    def __repr__(self):
        return f"<ErrorClassification(id={self.id}, code={self.code}, level={self.level})>"


class ErrorCatalog(Base, TenantScopedMixin, TimestampMixin):
    """
    Modelo para la tabla ErrorCatalog - Catálogo de Errores
    """

    __tablename__ = "error_catalogs"  # GCatErrores
    __table_args__ = (
        PrimaryKeyConstraint("id", name="error_catalogs_pkey"),
        UniqueConstraint("code", name="error_catalogs_code_unique"),
        ForeignKeyConstraint(
            ["classification_id"],
            ["a76.error_classifications.id"],
            name="fk_error_catalogs_classification",
        ),
        {"schema": "a76"},
    )

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

    # Error code (unique)
    code: Mapped[str] = mapped_column(String(15), nullable=False, unique=True)

    # Error information
    description: Mapped[Optional[str]] = mapped_column(String(255))

    # Foreign key to classification
    classification_id: Mapped[Optional[int]] = mapped_column(Integer)

    # Relationships
    classification: Mapped[Optional["ErrorClassification"]] = relationship(
        "ErrorClassification", back_populates="errors"
    )

    def __repr__(self):
        return f"<ErrorCatalog(id={self.id}, code={self.code}, description={self.description}, classification_id={self.classification_id})>"