from sqlalchemy import ForeignKey, Integer, Numeric, 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 Lead(Base, TenantScopedMixin, TimestampMixin):
    """Prospecto sin calificar. Al calificarse se convierte en cuenta/contacto/oportunidad."""

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

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    contact_name: Mapped[str | None] = mapped_column(String(160), nullable=True)
    email: Mapped[str | None] = mapped_column(String(255), nullable=True, index=True)
    phone: Mapped[str | None] = mapped_column(String(40), nullable=True)
    company_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
    # Origen: web | referido | evento | llamada | email | otro
    source: Mapped[str | None] = mapped_column(String(60), nullable=True)
    # Medio de contacto preferido (catálogo medio_contacto): llamada|correo|whatsapp|…
    preferred_contact_method: Mapped[str | None] = mapped_column(String(20), nullable=True)
    # Estado: new | contacted | qualified | unqualified | converted
    status: Mapped[str] = mapped_column(String(20), nullable=False, server_default=text("'new'"), index=True)
    estimated_value: Mapped[float | None] = mapped_column(Numeric(14, 2), nullable=True)
    owner_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    converted_account_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.accounts.id"), nullable=True
    )
    converted_contact_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.contacts.id"), nullable=True
    )
    converted_opportunity_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.opportunities.id"), nullable=True
    )
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
