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 Contact(Base, TenantScopedMixin, TimestampMixin):
    """Contacto CRM asociado a un cliente (``account_id``) o proveedor (``supplier_id``)."""

    __tablename__ = "contacts"
    __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
    )
    # Información personal
    first_name: Mapped[str] = mapped_column(String(120), nullable=False)
    last_name: Mapped[str | None] = mapped_column(String(120), nullable=True)
    job_title: Mapped[str | None] = mapped_column(String(120), nullable=True)  # puesto
    department: Mapped[str | None] = mapped_column(String(120), nullable=True)  # departamento
    area: Mapped[str | None] = mapped_column(String(120), nullable=True)  # ventas, operaciones, cobranza...
    # Información de contacto
    email: Mapped[str | None] = mapped_column(String(255), nullable=True, index=True)
    phone: Mapped[str | None] = mapped_column(String(40), nullable=True)
    extension: Mapped[str | None] = mapped_column(String(20), nullable=True)
    mobile: Mapped[str | None] = mapped_column(String(40), nullable=True)  # celular
    whatsapp: Mapped[str | None] = mapped_column(String(40), nullable=True)
    # Configuración
    is_primary: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
    receives_quotes: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
    receives_invoices: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
    receives_commercial_info: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
    status: Mapped[str] = mapped_column(String(20), nullable=False, server_default=text("'active'"))
    owner_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
