from decimal import Decimal

from api.v1.modules.crm.accounts import service as accounts_service
from api.v1.modules.crm.accounts.dto import AccountCreate
from api.v1.modules.crm.quotes import service as quotes_service
from api.v1.modules.crm.quotes.dto import QuoteCreate, QuoteItemCreate
from api.v1.modules.fin.invoices import service
from api.v1.modules.fin.invoices.dto import (
    InvoiceCreate,
    InvoiceItemCreate,
    InvoiceItemUpdate,
    InvoiceUpdate,
    PaymentCreate,
)
from api.v1.modules.ops.shipments import service as shipments_service
from api.v1.modules.ops.shipments.dto import ShipmentCloseInput, ShipmentCreate

T, C = 1, 1


def test_invoice_totals_with_tax(db):
    inv = service.create_invoice(db, InvoiceCreate(reference="F-001", currency="MXN", tax_rate=Decimal("16")), T, C)
    service.create_item(db, InvoiceItemCreate(invoice_id=inv.id, concept="flete_internacional", quantity=1, unit_amount=1000), T, C)
    service.create_item(db, InvoiceItemCreate(invoice_id=inv.id, concept="despacho_aduanal", quantity=1, unit_amount=500), T, C)
    inv = service.get_invoice(db, inv.id, T, C)
    assert float(inv.subtotal) == 1500.0
    assert float(inv.tax_amount) == 240.0  # 16% de 1500
    assert float(inv.total) == 1740.0
    assert float(inv.balance) == 1740.0


def test_payment_marks_paid(db):
    inv = service.create_invoice(db, InvoiceCreate(reference="F-002", tax_rate=Decimal("0")), T, C)
    service.create_item(db, InvoiceItemCreate(invoice_id=inv.id, concept="otros", quantity=1, unit_amount=1000), T, C)
    service.emit_invoice(db, inv.id, T, C)
    service.create_payment(db, PaymentCreate(invoice_id=inv.id, amount=Decimal("400"), method="transferencia"), T, C)
    inv = service.get_invoice(db, inv.id, T, C)
    assert float(inv.paid_amount) == 400.0 and float(inv.balance) == 600.0
    assert inv.status == "emitida"
    service.create_payment(db, PaymentCreate(invoice_id=inv.id, amount=Decimal("600")), T, C)
    inv = service.get_invoice(db, inv.id, T, C)
    assert float(inv.balance) == 0.0 and inv.status == "pagada" and inv.paid_at is not None


def test_generate_from_shipment_copies_quote_items(db):
    acc = accounts_service.create_account(db, AccountCreate(name="Cliente"), T, C)
    quote = quotes_service.create_quote(db, QuoteCreate(reference="COT-9", account_id=acc.id, currency="USD"), T, C)
    quotes_service.create_quote_item(db, QuoteItemCreate(quote_id=quote.id, concept="flete_internacional", quantity=1, unit_cost=1000, unit_sale=1500), T, C)
    quotes_service.accept_quote(db, quote.id, T, C)
    shipment = shipments_service.create_shipment_from_quote(db, quote.id, T, C)
    # El embarque debe cerrarse operativamente antes de facturar (R-F-01)
    shipments_service.close_shipment(
        db, shipment.id, ShipmentCloseInput(actual_cost_total=Decimal("1000"), cost_currency="USD"), T, C
    )

    inv = service.generate_from_shipment(db, shipment.id, T, C)
    assert inv.shipment_id == shipment.id
    assert inv.account_id == acc.id
    assert inv.currency == "USD"
    assert float(inv.ops_cost_total) == 1000.0  # costos de operación arrastrados (R-F-02)
    items = service.get_items(db, inv.id, T, C)
    assert len(items) == 1 and float(items[0].unit_amount) == 1500.0
    assert float(inv.subtotal) == 1500.0


# ----- Impuestos derivados por partida (para el CFDI) -----
# El CFDI exige el desglose por partida, pero la factura captura un % global. El traslado de
# IVA se deriva de ese %; estas pruebas fijan que la derivación no invente ni borre nada.

def _iva_de(db, item_id):
    from api.v1.modules.fin.invoices.models import InvoiceItemTax
    return db.query(InvoiceItemTax).filter(
        InvoiceItemTax.invoice_item_id == item_id, InvoiceItemTax.deleted_at.is_(None)
    ).all()


def _obj_imp(db, code):
    from api.v1.modules.fin.catalogs.models import TaxObject
    return db.query(TaxObject).filter(TaxObject.code == code).first().id


def test_iva_se_deriva_cuando_la_partida_es_objeto_de_impuesto(db):
    inv = service.create_invoice(db, InvoiceCreate(reference="F-IVA", tax_rate=Decimal("16")), T, C)
    item = service.create_item(
        db,
        InvoiceItemCreate(invoice_id=inv.id, concept="flete_internacional", quantity=1,
                          unit_amount=1000, tax_object_id=_obj_imp(db, "02")),
        T, C,
    )
    taxes = _iva_de(db, item.id)
    assert len(taxes) == 1
    assert float(taxes[0].rate) == 0.16
    assert float(taxes[0].amount) == 160.0
    assert taxes[0].is_withholding is False


def test_sin_objeto_de_impuesto_no_se_deriva_nada(db):
    """ObjetoImp 01 con nodo de impuestos es motivo de rechazo del SAT."""
    inv = service.create_invoice(db, InvoiceCreate(reference="F-NOOBJ", tax_rate=Decimal("16")), T, C)
    item = service.create_item(
        db,
        InvoiceItemCreate(invoice_id=inv.id, concept="otros", quantity=1, unit_amount=1000,
                          tax_object_id=_obj_imp(db, "01")),
        T, C,
    )
    assert _iva_de(db, item.id) == []


def test_cambiar_el_porcentaje_recalcula_las_partidas(db):
    inv = service.create_invoice(db, InvoiceCreate(reference="F-REC", tax_rate=Decimal("16")), T, C)
    item = service.create_item(
        db,
        InvoiceItemCreate(invoice_id=inv.id, concept="otros", quantity=1, unit_amount=1000,
                          tax_object_id=_obj_imp(db, "02")),
        T, C,
    )
    service.update_invoice(db, inv.id, InvoiceUpdate(tax_rate=Decimal("8")), T, C)
    taxes = _iva_de(db, item.id)
    assert float(taxes[0].rate) == 0.08
    assert float(taxes[0].amount) == 80.0


def test_cambiar_el_importe_recalcula_el_iva(db):
    inv = service.create_invoice(db, InvoiceCreate(reference="F-IMP", tax_rate=Decimal("16")), T, C)
    item = service.create_item(
        db,
        InvoiceItemCreate(invoice_id=inv.id, concept="otros", quantity=1, unit_amount=1000,
                          tax_object_id=_obj_imp(db, "02")),
        T, C,
    )
    service.update_item(db, item.id, InvoiceItemUpdate(unit_amount=Decimal("2000")), T, C)
    assert float(_iva_de(db, item.id)[0].amount) == 320.0


def test_quitar_el_objeto_de_impuesto_retira_el_traslado(db):
    inv = service.create_invoice(db, InvoiceCreate(reference="F-QUITA", tax_rate=Decimal("16")), T, C)
    item = service.create_item(
        db,
        InvoiceItemCreate(invoice_id=inv.id, concept="otros", quantity=1, unit_amount=1000,
                          tax_object_id=_obj_imp(db, "02")),
        T, C,
    )
    assert len(_iva_de(db, item.id)) == 1
    service.update_item(db, item.id, InvoiceItemUpdate(tax_object_id=_obj_imp(db, "01")), T, C)
    assert _iva_de(db, item.id) == []


def test_la_derivacion_no_pisa_una_retencion_capturada(db):
    """Ajustar los impuestos a mano desactiva el automatismo para esa partida.

    Es la diferencia entre un valor por defecto útil y un automatismo que borra trabajo ajeno.
    """
    from api.v1.modules.fin.catalogs.models import Tax
    from api.v1.modules.fin.invoices import taxes_service

    inv = service.create_invoice(db, InvoiceCreate(reference="F-RET", tax_rate=Decimal("16")), T, C)
    item = service.create_item(
        db,
        InvoiceItemCreate(invoice_id=inv.id, concept="otros", quantity=1, unit_amount=1000,
                          tax_object_id=_obj_imp(db, "02")),
        T, C,
    )
    isr = db.query(Tax).filter(Tax.code == "001").first()
    taxes_service.set_item_tax(db, item.id, isr.id, Decimal("0.10"), True, T, C)

    iva = db.query(Tax).filter(Tax.code == "002").first()

    # Cambiar el % ya no debe tocar ESTA partida: ni la retención capturada ni el IVA, que se
    # queda con la tasa que tenía cuando se intervino a mano.
    service.update_invoice(db, inv.id, InvoiceUpdate(tax_rate=Decimal("8")), T, C)
    taxes = {t.tax_id: t for t in _iva_de(db, item.id)}
    assert len(taxes) == 2, "se perdió un impuesto capturado a mano"
    assert float(taxes[isr.id].amount) == 100.0, "se pisó la retención"
    # Éste es el assert que distingue: sin el guard, el IVA habría bajado a 0.08 / 80.0.
    assert float(taxes[iva.id].rate) == 0.16, "el automatismo recalculó una partida intervenida"
    assert float(taxes[iva.id].amount) == 160.0
