from datetime import date, datetime

from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Index, 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

from ..catalogs.models import (  # noqa: F401  (registra los catálogos SAT referidos por las FK)
    PaymentForm,
    PaymentMethod,
    ProductService,
    Tax,
    TaxObject,
    UnitOfMeasure,
    VoucherType,
)
from ..concepts.models import Concept  # noqa: F401


class Invoice(Base, TenantScopedMixin, TimestampMixin):
    """Factura (Diagrama 4). Integra los costos de la operación para cobro al cliente."""

    __tablename__ = "invoices"
    __table_args__ = {"schema": "fin"}

    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
    shipment_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("ops.shipments.id"), nullable=True, index=True
    )
    quote_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("crm.quotes.id"), nullable=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("'MXN'"))
    # borrador | emitida | enviada | en_revision_cliente | pagada | cancelada
    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)
    due_date: Mapped[date | None] = mapped_column(Date, nullable=True)
    subtotal: Mapped[float] = mapped_column(Numeric(14, 2), nullable=False, server_default=text("0"))
    tax_rate: Mapped[float] = mapped_column(Numeric(5, 2), nullable=False, server_default=text("0"))  # % IVA
    tax_amount: Mapped[float] = mapped_column(Numeric(14, 2), nullable=False, server_default=text("0"))
    total: Mapped[float] = mapped_column(Numeric(14, 2), nullable=False, server_default=text("0"))
    paid_amount: Mapped[float] = mapped_column(Numeric(14, 2), nullable=False, server_default=text("0"))
    balance: Mapped[float] = mapped_column(Numeric(14, 2), nullable=False, server_default=text("0"))
    # Costos reales de la operación traídos de Operaciones al cierre (R-F-02)
    ops_cost_total: Mapped[float | None] = mapped_column(Numeric(14, 2), nullable=True)
    bank_info: Mapped[str | None] = mapped_column(Text, nullable=True)  # datos bancarios
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    sent_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    paid_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    # ----- Envío al cliente (R-F-05): PDF almacenado en MinIO -----
    pdf_file_key: Mapped[str | None] = mapped_column(String(512), nullable=True)
    # ----- Revisión del cliente (R-F-06) -----
    client_reviewed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    client_approved: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
    review_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)
    # ----- Datos fiscales del CFDI (catálogos SAT) -----
    # Nullables: las facturas emitidas antes de existir los catálogos no los tienen.
    voucher_type_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("sat.voucher_types.id"), nullable=True
    )
    payment_form_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("sat.payment_forms.id"), nullable=True
    )
    payment_method_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("sat.payment_methods.id"), nullable=True
    )
    expedition_zip_code: Mapped[str | None] = mapped_column(String(5), nullable=True)
    # ----- Modo de timbrado (por factura, no por entorno) -----
    # 'pruebas' | 'produccion'. Determina el host del PAC y, con él, si el comprobante tiene
    # validez fiscal ante el SAT. Inmutable una vez que la factura tiene un timbre exitoso:
    # cambiarlo después falsearía el registro de con qué intención se emitió.
    stamping_mode: Mapped[str] = mapped_column(
        String(12), nullable=False, server_default=text("'pruebas'")
    )


class InvoiceItem(Base, TenantScopedMixin, TimestampMixin):
    """Concepto de una factura (transporte, flete, despacho, gastos en destino, otros)."""

    __tablename__ = "invoice_items"
    __table_args__ = {"schema": "fin"}

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    invoice_id: Mapped[int] = mapped_column(
        Integer, ForeignKey("fin.invoices.id"), nullable=False, index=True
    )
    # Texto libre histórico: lo consume el PDF actual y se conserva obligatorio.
    concept: Mapped[str] = mapped_column(String(60), nullable=False)
    description: Mapped[str | None] = mapped_column(String(255), nullable=True)
    quantity: Mapped[float] = mapped_column(Numeric(12, 2), nullable=False, server_default=text("1"))
    unit_amount: Mapped[float] = mapped_column(Numeric(14, 2), nullable=False, server_default=text("0"))
    # ----- Datos fiscales de la partida (catálogos SAT) -----
    concept_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("fin.concepts.id"), nullable=True, index=True
    )
    product_service_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("sat.products_services.id"), nullable=True
    )
    unit_of_measure_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("sat.units_of_measure.id"), nullable=True
    )
    tax_object_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("sat.tax_objects.id"), nullable=True
    )


class InvoiceItemTax(Base, TenantScopedMixin, TimestampMixin):
    """Impuesto trasladado o retenido de una partida de la factura.

    Es captura de detalle fiscal para el futuro CFDI: **no** interviene en el cálculo
    de subtotal/IVA/total de la factura, que sigue saliendo de ``invoices.tax_rate``.
    """

    __tablename__ = "invoice_item_taxes"
    __table_args__ = (
        Index(
            "uq_fin_invoice_item_taxes",
            "invoice_item_id", "tax_id", "is_withholding",
            unique=True,
            postgresql_where=text("deleted_at IS NULL"),
            sqlite_where=text("deleted_at IS NULL"),
        ),
        {"schema": "fin"},
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    invoice_item_id: Mapped[int] = mapped_column(
        Integer, ForeignKey("fin.invoice_items.id"), nullable=False, index=True
    )
    tax_id: Mapped[int] = mapped_column(Integer, ForeignKey("sat.taxes.id"), nullable=False)
    # false = trasladado (se cobra al cliente); true = retenido
    is_withholding: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
    rate: Mapped[float | None] = mapped_column(Numeric(8, 6), nullable=True)  # p. ej. 0.160000
    amount: Mapped[float] = mapped_column(Numeric(14, 2), nullable=False, server_default=text("0"))


class Payment(Base, TenantScopedMixin, TimestampMixin):
    """Pago (cobranza) aplicado a una factura."""

    __tablename__ = "payments"
    __table_args__ = {"schema": "fin"}

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    invoice_id: Mapped[int] = mapped_column(
        Integer, ForeignKey("fin.invoices.id"), nullable=False, index=True
    )
    amount: Mapped[float] = mapped_column(Numeric(14, 2), nullable=False)
    payment_date: Mapped[date | None] = mapped_column(Date, nullable=True)
    # transferencia | efectivo | cheque | tarjeta | otro
    method: Mapped[str | None] = mapped_column(String(40), nullable=True)
    reference: Mapped[str | None] = mapped_column(String(120), nullable=True)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
