from datetime import date, datetime

from sqlalchemy import Date, DateTime, 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 Opportunity(Base, TenantScopedMixin, TimestampMixin):
    """Oportunidad (negocio) que avanza por las etapas de un embudo."""

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

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    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
    )
    pipeline_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.pipelines.id"), nullable=True, index=True
    )
    stage_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.pipeline_stages.id"), nullable=True, index=True
    )
    amount: Mapped[float | None] = mapped_column(Numeric(14, 2), nullable=True)
    currency: Mapped[str] = mapped_column(String(3), nullable=False, server_default=text("'MXN'"))
    probability: Mapped[int | None] = mapped_column(Integer, nullable=True)
    # Estado del negocio: open | won | lost
    status: Mapped[str] = mapped_column(String(20), nullable=False, server_default=text("'open'"), index=True)
    expected_close_date: Mapped[date | None] = mapped_column(Date, nullable=True)
    closed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    won_date: Mapped[date | None] = mapped_column(Date, nullable=True)   # fecha en que se ganó
    lost_date: Mapped[date | None] = mapped_column(Date, nullable=True)  # fecha en que se perdió
    lost_reason: Mapped[str | None] = mapped_column(String(255), nullable=True)
    source: Mapped[str | None] = mapped_column(String(60), nullable=True)
    owner_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    # Dirección de la operación (importacion|exportacion): se hereda a Solicitud→Cotización→Embarque
    operation_type: Mapped[str | None] = mapped_column(String(20), nullable=True)
    reference: Mapped[str | None] = mapped_column(String(40), nullable=True, index=True)  # folio O...
    # Expediente (hilo maestro del trámite); nace aquí y se hereda hacia abajo
    case_id: Mapped[int | None] = mapped_column(Integer, ForeignKey("crm.cases.id"), nullable=True, index=True)
    # Solicitud generada al convertir la oportunidad (back-link idempotente)
    converted_service_request_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.service_requests.id"), nullable=True
    )
