from datetime import datetime

from sqlalchemy import DateTime, 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 Activity(Base, TenantScopedMixin, TimestampMixin):
    """Actividad CRM: llamada, reunión, tarea, correo o nota.

    Puede enlazarse a cualquier entidad del CRM mediante las FK opcionales.
    """

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

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    # Tipo: call | meeting | task | email | note
    activity_type: Mapped[str] = mapped_column(String(20), nullable=False)
    subject: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)
    # Estado: pending | completed | canceled
    status: Mapped[str] = mapped_column(String(20), nullable=False, server_default=text("'pending'"), index=True)
    due_date: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    completed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    account_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.accounts.id"), nullable=True, index=True
    )
    contact_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.contacts.id"), nullable=True, index=True
    )
    lead_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.leads.id"), nullable=True, index=True
    )
    opportunity_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.opportunities.id"), nullable=True, index=True
    )
    owner_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
