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 ServiceRequest(Base, TenantScopedMixin, TimestampMixin):
    """Solicitud de cotización / levantamiento de requerimientos (Diagrama 1, pasos 3-5).

    Captura los requerimientos logísticos de la operación que el cliente solicita
    cotizar (tipo de operación, medio de transporte, ruta, carga, Incoterm, etc.).
    """

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

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    reference: Mapped[str | None] = mapped_column(String(40), nullable=True, index=True)  # folio
    account_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.accounts.id"), nullable=True, index=True
    )
    # Oportunidad de origen: enlaza el embudo (primer contacto) con la cadena RFQ→cotización (R-C-02)
    opportunity_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.opportunities.id"), nullable=True, index=True
    )
    # importacion | exportacion
    operation_type: Mapped[str] = mapped_column(String(20), nullable=False)
    # maritimo | aereo | terrestre | ferroviario | multimodal
    transport_mode: Mapped[str | None] = mapped_column(String(20), nullable=True)
    # puerto_puerto | puerto_puerta | puerta_puerto | puerta_puerta
    service_type: Mapped[str | None] = mapped_column(String(20), nullable=True)
    incoterm: Mapped[str | None] = mapped_column(String(10), nullable=True)
    origin: Mapped[str | None] = mapped_column(String(160), nullable=True)
    destination: Mapped[str | None] = mapped_column(String(160), nullable=True)
    cargo_type: Mapped[str | None] = mapped_column(String(120), nullable=True)
    weight: Mapped[float | None] = mapped_column(Numeric(14, 3), nullable=True)
    volume: Mapped[float | None] = mapped_column(Numeric(14, 3), nullable=True)
    load_type: Mapped[str | None] = mapped_column(String(10), nullable=True)  # FCL | LCL
    container_equipment: Mapped[str | None] = mapped_column(String(120), nullable=True)
    commodity: Mapped[str | None] = mapped_column(Text, nullable=True)  # mercancía
    required_date: Mapped[date | None] = mapped_column(Date, nullable=True)
    # Agente en destino / contraparte (proveedor)
    destination_agent_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.suppliers.id"), nullable=True
    )
    requirements: Mapped[str | None] = mapped_column(Text, nullable=True)  # otros requerimientos
    # Contacto al cliente como etapa del flujo comercial (Diagrama 1, paso 2 — R-C-04)
    first_contact_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    first_contact_notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    # nueva | contacto | en_analisis | cotizada | aceptada | rechazada | liberada
    status: Mapped[str] = mapped_column(String(20), nullable=False, server_default=text("'nueva'"), index=True)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    owner_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    created_by: Mapped[str | None] = mapped_column(String(64), nullable=True)
    updated_by: Mapped[str | None] = mapped_column(String(64), nullable=True)


class RateRequest(Base, TenantScopedMixin, TimestampMixin):
    """Solicitud de tarifa a un proveedor para una solicitud de servicio (Diagrama 1, paso 6)."""

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

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    service_request_id: Mapped[int] = mapped_column(
        Integer, ForeignKey("crm.service_requests.id"), nullable=False, index=True
    )
    supplier_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.suppliers.id"), nullable=True, index=True
    )
    # flete_internacional | transporte_terrestre | despacho_aduanal | gastos_destino | otros
    concept: Mapped[str] = mapped_column(String(60), nullable=False)
    description: Mapped[str | None] = mapped_column(String(255), nullable=True)
    # solicitada | recibida | declinada
    status: Mapped[str] = mapped_column(String(20), nullable=False, server_default=text("'solicitada'"))
    rate_amount: Mapped[float | None] = mapped_column(Numeric(14, 2), nullable=True)
    currency: Mapped[str | None] = mapped_column(String(3), nullable=True)
    valid_until: Mapped[date | None] = mapped_column(Date, nullable=True)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
