"""
Tests du flux e-MCF v2 : verification des montants avant finalisation,
lecture des montants par groupe (A-Z), reprise de l'erreur 63, paiements.
"""

from decimal import Decimal
from unittest.mock import Mock, patch

from django.test import SimpleTestCase

from facturation.fiscal_amounts import emcf_amounts_from_response
from facturation.fiscal_exceptions import FiscalBusinessError

from .emcf_adapter import EmcfAdapter, emcf_payment_type, normalize_payments
from .tests import prepared_payload


def confirm_ok():
    return {
        "dateTime": "24/11/2026 10:00:00",
        "codeDEFDGI": "TEST-FACT-AAAA-BBBB-CCCC-DDDD",
        "counters": "10/20 FV",
        "nim": "CD01004241-1",
        "qrCode": "RDCDEF01;CD01004241-1;TESTFACTAAAABBBBCCCCDDDD;A2560363Q;20261124100000",
    }


def payload_ht(total_ttc="53360.00", total_vat="7360.00"):
    source = prepared_payload()
    source["company"]["currency_code"] = "CDF"
    source["totals"] = {"total_ttc": Decimal(total_ttc), "total_vat": Decimal(total_vat)}
    return source


@patch("dgi.emcf_adapter.journal")
@patch("dgi.emcf_adapter.EdefClient")
class EmcfV2FlowTests(SimpleTestCase):
    def _client(self, client_class, create_response):
        client = client_class.return_value
        client.info_status.return_value = {"status": True, "nif": "A2560363Q"}
        client.create_invoice.return_value = create_response
        client.confirm_invoice.return_value = confirm_ok()
        return client

    def test_matching_totals_are_confirmed_and_returned_by_group(self, client_class, _journal):
        client = self._client(
            client_class,
            {
                "uid": "uid-1", "tb": 16, "taa": 0, "tab": 53360, "hab": 46000, "vab": 7360,
                "trq": 8, "taq": 0, "ts": 0, "total": 53360, "vtotal": 7360,
            },
        )

        result = EmcfAdapter().fiscalize(Mock(pk=7), payload_ht())

        client.confirm_invoice.assert_called_once_with("uid-1", {"total": 53360, "vtotal": 7360})
        client.cancel_invoice.assert_not_called()
        amounts = result["fiscal_amounts"]
        self.assertEqual(amounts["source"], "EMCF")
        self.assertEqual(amounts["total"], "53360.00")
        self.assertEqual(amounts["groups"]["B"], {"rate": "16", "ttc": "53360.00", "ht": "46000.00", "tva": "7360.00"})

    def test_mismatching_totals_cancel_the_request_and_block_the_sale(self, client_class, _journal):
        # Cas reel : la DGI a calcule 4844.16 alors que FacControl encaissait 4800.00.
        client = self._client(client_class, {"uid": "uid-2", "total": 4844.16, "vtotal": 668.16})

        with self.assertRaisesMessage(FiscalBusinessError, "DGI TTC=4844.16"):
            EmcfAdapter().fiscalize(Mock(pk=8), payload_ht("4800.00", "662.07"))

        client.cancel_invoice.assert_called_once_with("uid-2")
        client.confirm_invoice.assert_not_called()

    def test_pending_duplicate_error_63_is_cancelled_then_resent_with_same_number(self, client_class, _journal):
        client = self._client(client_class, None)
        client.create_invoice.side_effect = [
            {
                "errorCode": "63",
                "errorDesc": "La facture existe deja dans les factures en attente avec numero de la facture "
                "'FV-2026-00564' uid 'e5af2ff9-0ac8-4924-b8b7-cc9da3a17db8'",
            },
            {"uid": "uid-3", "total": 53360, "vtotal": 7360},
        ]

        EmcfAdapter().fiscalize(Mock(pk=9), payload_ht())

        client.cancel_invoice.assert_called_once_with("e5af2ff9-0ac8-4924-b8b7-cc9da3a17db8")
        sent = [call.args[0]["rn"] for call in client.create_invoice.call_args_list]
        self.assertEqual(sent, ["FV-2026-00564", "FV-2026-00564"])

    def test_business_error_code_is_not_a_channel_failure(self, client_class, _journal):
        self._client(client_class, {"errorCode": "9", "errorDesc": "Le groupe de taxation au niveau des articles n'est pas valide"})

        with self.assertRaisesMessage(FiscalBusinessError, "erreur 9"):
            EmcfAdapter().fiscalize(Mock(pk=10), payload_ht())

    def test_reserved_tax_group_is_refused_before_calling_the_api(self, client_class, _journal):
        source = payload_ht()
        source["items"][0]["tax_group"] = "T"

        with self.assertRaisesMessage(FiscalBusinessError, "reserves"):
            EmcfAdapter().fiscalize(Mock(pk=11), source)

        client_class.return_value.create_invoice.assert_not_called()


class EmcfV2AmountsTests(SimpleTestCase):
    def test_response_fields_for_groups_q_to_z_use_trq_to_trz(self):
        amounts = emcf_amounts_from_response(
            {"ts": 230, "trs": 0, "tas": 1000, "has": 1000, "vas": 0, "trq": 8, "taq": 1080, "haq": 1000, "vaq": 80,
             "total": 2080, "vtotal": 80}
        )

        self.assertEqual(amounts["ts"], Decimal("230.00"))
        self.assertEqual(amounts["groups"]["Q"]["rate"], "8")
        self.assertEqual(amounts["groups"]["S"]["ttc"], "1000.00")
        self.assertNotIn("T", amounts["groups"])

    def test_payment_types_follow_the_api_enum(self):
        self.assertEqual(emcf_payment_type("02", "VIREMENT"), "VIREMENT")
        self.assertEqual(emcf_payment_type("MOBILE_MONEY"), "MOBILEMONEY")
        self.assertEqual(emcf_payment_type("CARTE"), "CARTEBANCAIRE")
        self.assertEqual(emcf_payment_type("CHEQUE"), "CHEQUES")

    def test_payments_are_brought_back_to_the_invoice_total(self):
        # Monnaie rendue deduite des especes.
        self.assertEqual(
            normalize_payments([{"name": "ESPECES", "amount": Decimal("5000")}], Decimal("4800")),
            [{"name": "ESPECES", "amount": 4800.0}],
        )
        # Solde non paye declare en credit.
        self.assertEqual(
            normalize_payments([{"name": "MOBILEMONEY", "amount": Decimal("1000")}], Decimal("4800")),
            [{"name": "MOBILEMONEY", "amount": 1000.0}, {"name": "CREDIT", "amount": 3800.0}],
        )
        # Sans paiement saisi : le montant encaisse en especes.
        self.assertEqual(normalize_payments([], Decimal("4800"), amount_paid=Decimal("4800")), [{"name": "ESPECES", "amount": 4800.0}])
