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

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


class Document(Base, TenantScopedMixin, TimestampMixin):
    """Documento de un cliente (``account_id``) o proveedor (``supplier_id``).

    Guarda los metadatos y una referencia al archivo (``file_key`` en MinIO/S3 o
    ``file_url`` externa). La subida binaria se hace vía la capa de storage.
    """

    __tablename__ = "documents"
    __table_args__ = {"schema": "crm"}

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    account_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.accounts.id"), nullable=True, index=True
    )
    supplier_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.suppliers.id"), nullable=True, index=True
    )
    # Documento adjunto a una solicitud de servicio (factura, packing list, MSDS, etc.)
    service_request_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.service_requests.id"), nullable=True, index=True
    )
    # constancia_fiscal | acta_constitutiva | identificacion | comprobante_domicilio |
    # contrato | presentacion | certificacion | licencia | convenio | tarifario | otro
    doc_type: Mapped[str] = mapped_column(String(60), nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    file_key: Mapped[str | None] = mapped_column(String(512), nullable=True)  # objeto en MinIO/S3
    file_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)  # o URL externa
    content_type: Mapped[str | None] = mapped_column(String(120), nullable=True)
    size_bytes: Mapped[int | None] = mapped_column(Integer, nullable=True)
    uploaded_by: Mapped[str | None] = mapped_column(String(64), nullable=True)
