from datetime import date, datetime

from sqlalchemy import JSON, Boolean, 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
    case_id: Mapped[int | None] = mapped_column(Integer, ForeignKey("crm.cases.id"), nullable=True, index=True)  # expediente
    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)

    # ----- Campos del documento maestro de cotización (T2026-08) -----
    # Datos generales
    contact_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.contacts.id"), nullable=True, index=True
    )
    request_date: Mapped[date | None] = mapped_column(Date, nullable=True)  # fecha de la solicitud
    currency: Mapped[str | None] = mapped_column(String(3), nullable=True)
    priority: Mapped[str | None] = mapped_column(String(20), nullable=True)  # baja|normal|alta|urgente
    # Ruta (país por catálogo ISO; ciudad/puerto por catálogo o texto libre)
    origin_country: Mapped[str | None] = mapped_column(String(3), nullable=True)
    origin_city: Mapped[str | None] = mapped_column(String(120), nullable=True)
    origin_port: Mapped[str | None] = mapped_column(String(20), nullable=True)
    destination_country: Mapped[str | None] = mapped_column(String(3), nullable=True)
    destination_city: Mapped[str | None] = mapped_column(String(120), nullable=True)
    destination_port: Mapped[str | None] = mapped_column(String(20), nullable=True)
    pickup_location: Mapped[str | None] = mapped_column(String(255), nullable=True)
    delivery_location: Mapped[str | None] = mapped_column(String(255), nullable=True)
    estimated_shipment_date: Mapped[date | None] = mapped_column(Date, nullable=True)
    # Mercancía
    cargo_value: Mapped[float | None] = mapped_column(Numeric(14, 2), nullable=True)
    insurance_required: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
    hs_code: Mapped[str | None] = mapped_column(String(20), nullable=True)  # fracción arancelaria
    goods_origin_country: Mapped[str | None] = mapped_column(String(3), nullable=True)  # país de origen de la mercancía
    hazardous_imo: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
    refrigerated: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
    stackable: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
    # Dimensiones y bultos
    pieces_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
    boxes_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
    pallets_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
    net_weight: Mapped[float | None] = mapped_column(Numeric(14, 3), nullable=True)  # peso neto (weight = bruto)
    length_cm: Mapped[float | None] = mapped_column(Numeric(10, 2), nullable=True)
    width_cm: Mapped[float | None] = mapped_column(Numeric(10, 2), nullable=True)
    height_cm: Mapped[float | None] = mapped_column(Numeric(10, 2), nullable=True)
    measurement_unit: Mapped[str | None] = mapped_column(String(20), nullable=True)
    # FCL
    container_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
    # LCL
    packaging_type: Mapped[str | None] = mapped_column(String(20), nullable=True)
    oversized: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
    weight_per_pallet: Mapped[float | None] = mapped_column(Numeric(14, 3), nullable=True)
    volume_per_pallet: Mapped[float | None] = mapped_column(Numeric(14, 3), nullable=True)
    # Servicios adicionales (lista de códigos del catálogo servicio_adicional) y pago
    additional_services: Mapped[list | None] = mapped_column(JSON, nullable=True)
    # Costo estimado por servicio adicional marcado: {codigo: costo}
    additional_service_costs: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    payment_method: Mapped[str | None] = mapped_column(String(20), nullable=True)
    # Notas
    client_notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    internal_notes: Mapped[str | None] = mapped_column(Text, 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)
