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

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


class Address(Base, TenantScopedMixin, TimestampMixin):
    """Dirección de un cliente (``account_id``) o proveedor (``supplier_id``).

    Un cliente/proveedor puede tener varias direcciones (fiscal, oficina, etc.).
    """

    __tablename__ = "addresses"
    __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
    )
    # fiscal | oficina | sucursal | bodega | patio | terminal | almacen
    address_type: Mapped[str] = mapped_column(String(20), nullable=False, server_default=text("'fiscal'"))
    street: Mapped[str | None] = mapped_column(String(255), nullable=True)  # calle
    ext_number: Mapped[str | None] = mapped_column(String(30), nullable=True)  # número exterior
    int_number: Mapped[str | None] = mapped_column(String(30), nullable=True)  # número interior
    neighborhood: Mapped[str | None] = mapped_column(String(120), nullable=True)  # colonia
    postal_code: Mapped[str | None] = mapped_column(String(10), nullable=True)  # código postal
    city: Mapped[str | None] = mapped_column(String(120), nullable=True)  # municipio
    state: Mapped[str | None] = mapped_column(String(120), nullable=True)  # estado (código catálogo)
    # País como código ISO 3166 alfa-3 del catálogo (p. ej. MEX). Ampliado de 2→3.
    country: Mapped[str | None] = mapped_column(String(3), nullable=True, server_default=text("'MEX'"))
    reference_notes: Mapped[str | None] = mapped_column(Text, nullable=True)  # referencias
    is_primary: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
