"""Tests du choix du canal fiscal par defaut et du repli entre MCF et e-MCF."""

from unittest.mock import Mock, patch

from django.test import SimpleTestCase
from django.utils import translation

from .fiscal_exceptions import FiscalBusinessError, FiscalFallbackRequired, FiscalTechnicalError
from .fiscal_orchestrator import FiscalOrchestrator


SECURITY = {"code_def_dgi": "SIG-1", "counters": "1/1 FV", "nim": "NIM-1", "qr_code": "QR-1"}
DGI_UNAVAILABLE_FR = "Le serveur de la DGI FACNO est indisponible. Veuillez réessayer plus tard."


class FiscalOrchestratorFallbackTests(SimpleTestCase):
    """Canal par defaut d'abord, puis l'autre canal ; message unique si les deux sont indisponibles."""

    def _fiscalize(self, outcomes, *, primary="MCF", fallback_mode="AUTO", allow_fallback=False):
        """
        Fiscalise avec des canaux simules.

        `outcomes` associe a chaque canal une exception a lever ; un canal
        absent repond avec des elements de securite. Les canaux appeles sont
        conserves dans `self.calls`.
        """

        self.calls = []
        payload = {
            "fiscal_transaction_id": "tx-1",
            "commande": {"numero": "FV-2026-00001"},
            "policy": {"primary_channel": primary, "fallback_mode": fallback_mode, "require_security_before_save": True},
        }

        def call_channel(channel, commande, prepared_payload):
            self.calls.append(channel)
            if channel in outcomes:
                raise outcomes[channel]
            return {"channel": channel, "security": SECURITY}

        with patch("facturation.fiscal_orchestrator.FiscalPayloadBuilder") as builder, patch.object(
            FiscalOrchestrator, "_call_channel", side_effect=call_channel
        ), patch.object(FiscalOrchestrator, "_apply_security_elements"):
            builder.return_value.build.return_value = payload
            return FiscalOrchestrator().fiscalize_commande(Mock(pk=1, numero="FV-2026-00001"), allow_fallback=allow_fallback)

    def test_default_channel_from_configuration_is_used_first(self):
        """Verifie que seul le canal par defaut est appele quand il repond."""

        result = self._fiscalize({}, primary="MCF")

        self.assertEqual(result["channel"], "MCF")
        self.assertEqual(self.calls, ["MCF"])

    def test_unavailable_default_channel_falls_back_to_the_other_channel(self):
        """Verifie qu'un MCF non connecte laisse l'e-MCF valider la facture."""

        result = self._fiscalize({"MCF": FiscalTechnicalError("Vous n'avez pas de MCF physique connecte.")})

        self.assertEqual(result["channel"], "EMCF")
        self.assertEqual(self.calls, ["MCF", "EMCF"])

    def test_ask_user_mode_asks_before_using_the_other_channel(self):
        """Verifie la confirmation demandee puis le repli une fois la confirmation donnee."""

        outcomes = {"MCF": FiscalTechnicalError("MCF absent")}

        with self.assertRaises(FiscalFallbackRequired) as raised:
            self._fiscalize(outcomes, fallback_mode="ASK_USER")
        self.assertEqual((raised.exception.primary_channel, raised.exception.fallback_channel), ("MCF", "EMCF"))
        self.assertEqual(self.calls, ["MCF"])

        result = self._fiscalize(outcomes, fallback_mode="ASK_USER", allow_fallback=True)
        self.assertEqual(result["channel"], "EMCF")

    def test_both_channels_unavailable_return_single_dgi_message(self):
        """Verifie le message unique, et les causes de chaque canal dans les logs."""

        outcomes = {
            "MCF": FiscalTechnicalError("MCF absent"),
            "EMCF": FiscalTechnicalError("Le serveur e-MCF a refuse le token API EDEF / DGI (HTTP 401)"),
        }

        with translation.override("fr"), self.assertLogs("facturation.fiscal_orchestrator", "WARNING") as logs:
            with self.assertRaises(FiscalTechnicalError) as raised:
                self._fiscalize(outcomes, fallback_mode="ASK_USER", allow_fallback=True)

        self.assertNotIsInstance(raised.exception, FiscalFallbackRequired)
        self.assertEqual(str(raised.exception), DGI_UNAVAILABLE_FR)
        self.assertIn("MCF absent", logs.output[0])
        self.assertIn("HTTP 401", logs.output[0])

        with translation.override("en"), self.assertLogs("facturation.fiscal_orchestrator", "WARNING"):
            with self.assertRaisesMessage(FiscalTechnicalError, "The DGI FACNO server is unavailable. Please try again later."):
                self._fiscalize(outcomes, primary="EMCF")

    def test_disabled_fallback_keeps_the_default_channel_error(self):
        """Verifie qu'aucun autre canal n'est tente quand le repli est desactive."""

        with self.assertRaisesMessage(FiscalTechnicalError, "MCF absent"):
            self._fiscalize({"MCF": FiscalTechnicalError("MCF absent")}, fallback_mode="DISABLED")
        self.assertEqual(self.calls, ["MCF"])

    def test_business_error_on_the_other_channel_is_not_hidden(self):
        """Verifie qu'une facture refusee par le second canal garde son message precis."""

        outcomes = {
            "MCF": FiscalTechnicalError("MCF absent"),
            "EMCF": FiscalBusinessError("L'ISF societe est obligatoire pour le canal e-MCF."),
        }

        with self.assertRaisesMessage(FiscalBusinessError, "L'ISF societe est obligatoire"):
            self._fiscalize(outcomes)
