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 Quote(Base, TenantScopedMixin, TimestampMixin):
    """Cotización (Diagrama 1, pasos 7-9). Integra los conceptos de costo/venta."""

    __tablename__ = "quotes"
    __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)
    case_id: Mapped[int | None] = mapped_column(Integer, ForeignKey("crm.cases.id"), nullable=True, index=True)  # expediente
    service_request_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.service_requests.id"), nullable=True, index=True
    )
    account_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.accounts.id"), nullable=True, index=True
    )
    currency: Mapped[str] = mapped_column(String(3), nullable=False, server_default=text("'USD'"))
    # Variante de carga cuando la solicitud es "Ambas": FCL | LCL (NULL si no aplica)
    load_type: Mapped[str | None] = mapped_column(String(10), nullable=True)
    # borrador | enviada | aceptada | rechazada
    status: Mapped[str] = mapped_column(String(20), nullable=False, server_default=text("'borrador'"), index=True)
    issue_date: Mapped[date | None] = mapped_column(Date, nullable=True)
    valid_until: Mapped[date | None] = mapped_column(Date, nullable=True)
    total_cost: Mapped[float] = mapped_column(Numeric(14, 2), nullable=False, server_default=text("0"))
    total_sale: Mapped[float] = mapped_column(Numeric(14, 2), nullable=False, server_default=text("0"))
    sent_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    accepted_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    rejected_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    terms: Mapped[str | None] = mapped_column(Text, nullable=True)
    owner_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    # Clave del PDF generado en MinIO (para regenerar/enviar)
    pdf_file_key: Mapped[str | None] = mapped_column(String(512), nullable=True)
    created_by: Mapped[str | None] = mapped_column(String(64), nullable=True)
    updated_by: Mapped[str | None] = mapped_column(String(64), nullable=True)


class QuoteSettings(Base, TenantScopedMixin, TimestampMixin):
    """Configuración de marca del formato de cotización, por compañía (tenant).

    Encabezado del emisor, logo y textos por defecto que se imprimen en el PDF.
    """

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

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    emitter_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
    emitter_rfc: Mapped[str | None] = mapped_column(String(13), nullable=True)
    emitter_address: Mapped[str | None] = mapped_column(Text, nullable=True)
    emitter_phone: Mapped[str | None] = mapped_column(String(60), nullable=True)
    emitter_email: Mapped[str | None] = mapped_column(String(255), nullable=True)
    emitter_website: Mapped[str | None] = mapped_column(String(255), nullable=True)
    logo_file_key: Mapped[str | None] = mapped_column(String(512), nullable=True)
    accent_color: Mapped[str | None] = mapped_column(String(9), nullable=True, server_default=text("'#2f6bf0'"))
    quote_prefix: Mapped[str | None] = mapped_column(String(12), nullable=True, server_default=text("'COT'"))
    default_terms: Mapped[str | None] = mapped_column(Text, nullable=True)
    footer_note: Mapped[str | None] = mapped_column(Text, nullable=True)


class QuoteItem(Base, TenantScopedMixin, TimestampMixin):
    """Concepto de una cotización (flete, transporte terrestre, despacho, gastos destino, otros)."""

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

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    quote_id: Mapped[int] = mapped_column(
        Integer, ForeignKey("crm.quotes.id"), nullable=False, 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)
    supplier_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.suppliers.id"), nullable=True
    )
    quantity: Mapped[float] = mapped_column(Numeric(12, 2), nullable=False, server_default=text("1"))
    unit_cost: Mapped[float] = mapped_column(Numeric(14, 2), nullable=False, server_default=text("0"))
    unit_sale: Mapped[float] = mapped_column(Numeric(14, 2), nullable=False, server_default=text("0"))
    currency: Mapped[str | None] = mapped_column(String(3), nullable=True)
