"""
Modelo ORM para catálogo de localización (a76).
Tabla compartida para contexto Fixed Asset (FA) e inventory.
"""

import enum
from typing import Optional

from sqlalchemy import Integer, String, Text, UniqueConstraint, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column

from api.v1.common.base_models import TenantScopedMixin, TimestampMixin
from core.database import Base


class LocationSystem(str, enum.Enum):
    """Contexto de uso de la localización."""
    FIXED_ASSET = "fixed_asset"
    INVENTORY = "inventory"


class Location(Base, TenantScopedMixin, TimestampMixin):
    """
    Catálogo de localización (clave + localizacion), compartido por FA e inventory.
    """

    __tablename__ = "location"
    __table_args__ = (
        UniqueConstraint(
            "clave_localizacion",
            "tenant_id",
            "company_id",
            "system",
            name="uq_location_clave_tenant_company_system",
        ),
        {"schema": "a76"},
    )

    id: Mapped[int] = mapped_column(
        Integer, primary_key=True, autoincrement=True
    )
    clave_localizacion: Mapped[str] = mapped_column(String(20), nullable=False)
    localizacion: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
    system: Mapped[str] = mapped_column(
        String(20), nullable=False
    )  # 'fixed_asset' | 'inventory'

    def __repr__(self) -> str:
        return (
            f"<Location(id={self.id}, clave_localizacion={self.clave_localizacion!r}, "
            f"localizacion={self.localizacion!r}, system={self.system!r})>"
        )


class FaLocationExt(Base, TenantScopedMixin, TimestampMixin):
    """
    Extra info for Fixed Asset locations only (1:1 with Location).
    Table: Fa_Location_Ext (fa_location_ext).
    """

    __tablename__ = "fa_location_ext"
    __table_args__ = (
        UniqueConstraint("location_id", name="uq_fa_location_ext_location_id"),
        {"schema": "a76"},
    )

    id: Mapped[int] = mapped_column(
        Integer, primary_key=True, autoincrement=True
    )
    location_id: Mapped[int] = mapped_column(
        Integer,
        ForeignKey("a76.location.id", ondelete="CASCADE"),
        nullable=False,
        unique=True,
    )
    department: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
    responsible: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
    observations: Mapped[Optional[str]] = mapped_column(Text, nullable=True)

    def __repr__(self) -> str:
        return (
            f"<FaLocationExt(id={self.id}, location_id={self.location_id}, "
            f"department={self.department!r})>"
        )
