from decimal import Decimal
from types import SimpleNamespace

from api.v1.modules.a76.invoices.models import Currency
from api.v1.modules.a76.invoices.imports.process.sub_process.assing_values_def_mex import (
    assign_values_iva_lines,
)


def _mk_line(qty: str, capture: str):
    return SimpleNamespace(
        quantity=SimpleNamespace(quantity=Decimal(qty)),
        financial=SimpleNamespace(
            unit_cost_capture=Decimal(capture),
            unit_cost_usd=None,
            unit_cost_mxn=None,
            unit_cost_mc=None,
            sub_import_value_usd=None,
            sub_import_value_mxn=None,
            sub_import_value_mc=None,
            vat_usd=None,
            vat_mxn=None,
            vat_mc=None,
            value_usd=None,
            value_mxn=None,
            value_mc=None,
        ),
    )


def _mk_invoice(currency: Currency):
    return SimpleNamespace(
        financials=SimpleNamespace(
            currency=currency,
            exchange_rate=Decimal("17.25"),
            exchange_rate_mm=Decimal("1.10"),
            iva_factor="16",
        )
    )


def test_assign_values_iva_lines_currency_me():
    invoice = _mk_invoice(Currency.FOREIGN)
    line = _mk_line("10", "2")
    assign_values_iva_lines(invoice, [line])

    assert line.financial.sub_import_value_usd == Decimal("20")
    assert line.financial.vat_usd == Decimal("3.2")
    assert line.financial.value_usd == Decimal("23.2")
    assert line.financial.unit_cost_mxn == Decimal("34.50")


def test_assign_values_iva_lines_currency_mn():
    invoice = _mk_invoice(Currency.LOCAL)
    line = _mk_line("5", "100")
    assign_values_iva_lines(invoice, [line])

    assert line.financial.sub_import_value_mxn == Decimal("500")
    assert line.financial.vat_mxn == Decimal("80")
    assert line.financial.value_mxn == Decimal("580")
    assert line.financial.unit_cost_usd == Decimal("5.797101449275362318840579710")


def test_assign_values_iva_lines_currency_mc():
    invoice = _mk_invoice(Currency.MANUAL)
    line = _mk_line("4", "3")
    assign_values_iva_lines(invoice, [line])

    assert line.financial.sub_import_value_mc == Decimal("12")
    assert line.financial.vat_mc == Decimal("1.92")
    assert line.financial.value_mc == Decimal("13.92")
    assert line.financial.unit_cost_usd == Decimal("3.30")
