import json
from decimal import Decimal
from types import SimpleNamespace
from unittest.mock import patch

from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse

from dgi.models import ItemType, TaxGroup
from dgi.emcf_adapter import EmcfAdapter
from G_Affectation.models import MentionPointDeVente, ParametrePointDeVente
from facturation.fiscal_preparation import FiscalPayloadBuilder
from facturation.models import (
    Client, Commande, Configuration, LigneCommande, PointDeVente, Produit, ProduitPointVentePrix,
    StockPointDeVente, UserMenuPermission,
)
from facturation.price_utils import enregistrer_changement_prix_standard
from facturation.serializers import POSSaleSerializer
from proforma.services import ProformaCreationService

from .models import ConfigurationTaux, HistoriqueTaux, RegleTaux
from .services import (
    TauxNonConfigureError,
    convertir_prix_usd_en_cdf,
    enregistrer_configuration,
    enregistrer_regle,
    equivalent_usd,
    points_sans_taux,
    resolutions_des_points,
    resoudre_taux,
    taux_configure,
    taux_configures,
    taux_pour_point_de_vente,
)


class GestionTauxTests(TestCase):
    def setUp(self):
        self.mention = MentionPointDeVente.objects.create(nom="Magasins")
        self.other_mention = MentionPointDeVente.objects.create(nom="Supermarchés")
        self.pdv_a = PointDeVente.objects.create(nom="Magasin A")
        self.pdv_b = PointDeVente.objects.create(nom="Magasin B")
        self.pdv_c = PointDeVente.objects.create(nom="Supermarché C")
        ParametrePointDeVente.objects.create(point_de_vente=self.pdv_a, mention=self.mention)
        ParametrePointDeVente.objects.create(point_de_vente=self.pdv_b, mention=self.mention)
        ParametrePointDeVente.objects.create(point_de_vente=self.pdv_c, mention=self.other_mention)

        self.admin = get_user_model().objects.create_user(
            username="admin-rates", email="admin-rates@example.com", password="secret", role="ADMIN",
            point_de_vente=self.pdv_a,
        )
        self.global_admin = get_user_model().objects.create_user(
            username="global-admin-rates", email="global-admin-rates@example.com",
            password="secret", role="ADMIN", point_de_vente=self.pdv_a,
        )
        self.global_admin.points_de_vente.add(self.pdv_b, self.pdv_c)
        self.default_admin = get_user_model().objects.create_user(
            username="default-admin-rates", email="default-admin-rates@example.com",
            password="secret", role="ADMIN", point_de_vente=self.pdv_a,
            est_administrateur_par_defaut=True,
        )
        self.seller = get_user_model().objects.create_user(
            username="seller-rates", email="seller-rates@example.com", password="secret", point_de_vente=self.pdv_a,
        )
        self.config = Configuration.objects.create(
            taux_change=Decimal("2800"), mode_dgi="ttc", type_dgi="FV",
            nif="A1234567Q", isf_dgi="CD01000000-1",
        )
        self.item_type = ItemType.objects.create(code="BIE-RATE", name="Bien")
        # Groupe valide (A a S) : l'e-MCF v2 refuse tout autre code.
        self.tax_group, _ = TaxGroup.objects.update_or_create(
            code="A", defaults={"name": "GROUPE A (EXONERE)", "tax": Decimal("0"), "is_active": True}
        )
        self.product = Produit.objects.create(
            nom="Produit en dollar", code_sku="RATE-001", unite_mesure="Pièce",
            prix_vente=Decimal("1"), taxgroup=self.tax_group, typeart=self.item_type, actif=True,
        )
        self.packaging = self.product.conditionnements.get()
        StockPointDeVente.objects.create(
            point_de_vente=self.pdv_a, produit=self.product, quantite=Decimal("20"),
        )
        self.customer = Client.objects.create(nom_complet="Client taux")

    def _mode_par_cible(self):
        enregistrer_configuration(
            mode=ConfigurationTaux.MODE_PAR_CIBLE, taux_global=Decimal("2300"), user=self.admin,
        )

    def test_rule_on_a_point_applies_to_that_point_only(self):
        self._mode_par_cible()
        enregistrer_regle(point_de_vente=self.pdv_a, taux=Decimal("2200"), user=self.admin)

        self.assertEqual(taux_pour_point_de_vente(self.pdv_a), Decimal("2200"))
        # Magasin B porte la même mention, mais la règle ne vise que Magasin A.
        self.assertIsNone(resoudre_taux(self.pdv_b).taux)
        self.assertIsNone(resoudre_taux(self.pdv_c).taux)

    def test_rule_on_a_mention_applies_to_all_its_points_and_no_other(self):
        self._mode_par_cible()
        enregistrer_regle(mention=self.mention, taux=Decimal("2900"), user=self.admin)

        self.assertEqual(taux_pour_point_de_vente(self.pdv_a), Decimal("2900"))
        self.assertEqual(taux_pour_point_de_vente(self.pdv_b), Decimal("2900"))
        self.assertIsNone(resoudre_taux(self.pdv_c).taux)

        # Le point qui a sa propre règle la garde ; les autres suivent la mention.
        enregistrer_regle(point_de_vente=self.pdv_b, taux=Decimal("2200"), user=self.admin)
        self.assertEqual(taux_pour_point_de_vente(self.pdv_a), Decimal("2900"))
        self.assertEqual(taux_pour_point_de_vente(self.pdv_b), Decimal("2200"))

    def test_changing_the_mode_switches_the_rate_and_keeps_the_rules(self):
        enregistrer_regle(mention=self.mention, taux=Decimal("2900"), user=self.admin)

        enregistrer_configuration(mode=ConfigurationTaux.MODE_GLOBAL, taux_global=Decimal("2300"), user=self.admin)
        self.assertEqual(taux_pour_point_de_vente(self.pdv_a), Decimal("2300"))
        self.assertEqual(taux_pour_point_de_vente(self.pdv_c), Decimal("2300"))

        self._mode_par_cible()
        self.assertEqual(taux_pour_point_de_vente(self.pdv_a), Decimal("2900"))
        self.assertIsNone(resoudre_taux(self.pdv_c).taux)

        enregistrer_configuration(mode=ConfigurationTaux.MODE_GLOBAL, taux_global=Decimal("2500"), user=self.admin)
        self.assertEqual(taux_pour_point_de_vente(self.pdv_a), Decimal("2500"))
        self.assertTrue(RegleTaux.objects.filter(mention=self.mention).exists())

    def test_inactive_rule_is_ignored(self):
        self._mode_par_cible()
        enregistrer_regle(mention=self.mention, taux=Decimal("2900"), user=self.admin)
        enregistrer_regle(point_de_vente=self.pdv_a, taux=Decimal("2200"), actif=False, user=self.admin)
        self.assertEqual(taux_pour_point_de_vente(self.pdv_a), Decimal("2900"))

        enregistrer_regle(mention=self.mention, taux=Decimal("2900"), actif=False, user=self.admin)
        self.assertIsNone(resoudre_taux(self.pdv_a).taux)

    def test_resolution_of_several_points_is_identical_and_does_not_query_per_point(self):
        self._mode_par_cible()
        enregistrer_regle(mention=self.mention, taux=Decimal("2900"), user=self.admin)
        enregistrer_regle(point_de_vente=self.pdv_a, taux=Decimal("2200"), user=self.admin)
        points = [self.pdv_a, self.pdv_b, self.pdv_c]

        with self.assertNumQueries(4):
            resolutions = resolutions_des_points(points)

        for point in points:
            self.assertEqual(resolutions[point.pk], resoudre_taux(point))

    def test_configured_rate_never_returns_the_neutral_one(self):
        self.config.taux_change = 0
        self.config.save(update_fields=["taux_change"])
        self.assertEqual(taux_pour_point_de_vente(self.pdv_a), Decimal("1"))
        self.assertIsNone(taux_configure(self.pdv_a))
        self.assertEqual(taux_configures([self.pdv_a]), {self.pdv_a.pk: None})

        enregistrer_configuration(mode=ConfigurationTaux.MODE_GLOBAL, taux_global=Decimal("2400"), user=self.admin)
        self.assertEqual(taux_configure(self.pdv_a), Decimal("2400"))
        self.assertEqual(taux_configure(), Decimal("2400"))

    def test_only_active_points_of_target_mode_are_reported_without_rate(self):
        self.assertEqual(points_sans_taux([self.pdv_a, self.pdv_c]), [])

        self._mode_par_cible()
        enregistrer_regle(mention=self.mention, taux=Decimal("2900"), user=self.admin)
        self.assertEqual(points_sans_taux([self.pdv_a, self.pdv_b, self.pdv_c]), [self.pdv_c])

        self.pdv_c.actif = False
        self.pdv_c.save(update_fields=["actif"])
        self.assertEqual(points_sans_taux([self.pdv_a, self.pdv_b, self.pdv_c]), [])

    def test_management_screen_names_the_points_that_cannot_invoice(self):
        self.client.force_login(self.global_admin)
        self.assertNotContains(self.client.get(reverse("g_taux:gestion")), "rate-coverage-alert")

        self._mode_par_cible()
        enregistrer_regle(mention=self.mention, taux=Decimal("2900"), user=self.admin)
        response = self.client.get(reverse("g_taux:gestion"))

        self.assertContains(response, "rate-coverage-alert")
        self.assertEqual(response.context["points_sans_taux"], [self.pdv_c])
        self.assertContains(response, "Points de vente sans taux")

        english = self.client.get(reverse("g_taux:gestion"), HTTP_ACCEPT_LANGUAGE="en")
        self.assertContains(english, "Points of sale without a rate")

    def test_rule_window_says_which_points_will_use_the_rate(self):
        self.client.force_login(self.global_admin)

        response = self.client.get(reverse("g_taux:gestion"))

        self.assertEqual(
            response.context["noms_points_par_mention"][self.mention.pk],
            ["Magasin A", "Magasin B"],
        )
        self.assertContains(response, 'id="rate-mention-points"')
        self.assertContains(response, "Seul ce point de vente utilisera ce taux.")
        # Mode général actif : la règle ne s'appliquera pas tout de suite, et la page le dit.
        self.assertContains(response, "Le mode général est actif")
        self._mode_par_cible()
        self.assertNotContains(self.client.get(reverse("g_taux:gestion")), "Le mode général est actif")

    def test_usd_equivalent_uses_the_rate_of_each_document(self):
        self.assertEqual(
            equivalent_usd([(Decimal("2000"), Decimal("2000")), (Decimal("2500"), Decimal("5000"))]),
            (Decimal("3.00"), None),
        )
        self.assertEqual(equivalent_usd([(Decimal("2000"), Decimal("3000"))]), (Decimal("1.50"), Decimal("2000")))
        self.assertEqual(equivalent_usd([(None, Decimal("3000"))]), (Decimal("0.00"), None))
        self.assertEqual(equivalent_usd([]), (Decimal("0.00"), None))

    def test_legacy_global_rate_is_used_before_module_configuration_exists(self):
        self.assertEqual(taux_pour_point_de_vente(self.pdv_a), Decimal("2800"))
        self.assertEqual(resoudre_taux(self.pdv_a).source, "global")

    def test_global_mode_forces_same_rate_even_when_target_rules_exist(self):
        enregistrer_configuration(
            mode=ConfigurationTaux.MODE_GLOBAL, taux_global=Decimal("2500"), user=self.admin,
        )
        enregistrer_regle(point_de_vente=self.pdv_a, taux=Decimal("2700"), user=self.admin)
        self.assertEqual(taux_pour_point_de_vente(self.pdv_a), Decimal("2500"))
        self.assertEqual(taux_pour_point_de_vente(self.pdv_c), Decimal("2500"))
        self.config.refresh_from_db()
        self.assertEqual(self.config.taux_change, Decimal("2500"))

    def test_target_mode_uses_point_then_mention_without_global_fallback(self):
        enregistrer_configuration(
            mode=ConfigurationTaux.MODE_PAR_CIBLE, taux_global=Decimal("2400"), user=self.admin,
        )
        enregistrer_regle(mention=self.mention, taux=Decimal("2600"), user=self.admin)
        enregistrer_regle(point_de_vente=self.pdv_a, taux=Decimal("2750"), user=self.admin)
        self.assertEqual((taux_pour_point_de_vente(self.pdv_a), resoudre_taux(self.pdv_a).source), (Decimal("2750"), "point_de_vente"))
        self.assertEqual((taux_pour_point_de_vente(self.pdv_b), resoudre_taux(self.pdv_b).source), (Decimal("2600"), "mention"))
        self.assertIsNone(resoudre_taux(self.pdv_c).taux)
        with self.assertRaises(TauxNonConfigureError):
            taux_pour_point_de_vente(self.pdv_c)

    def test_target_mode_converts_prices_for_point_and_mention_only(self):
        """Le prix USD suit le PDV puis la mention, sans jamais prendre le global."""

        enregistrer_configuration(
            mode=ConfigurationTaux.MODE_PAR_CIBLE,
            taux_global=Decimal("2400"),
            user=self.admin,
        )
        enregistrer_regle(mention=self.mention, taux=Decimal("2600"), user=self.admin)
        enregistrer_regle(point_de_vente=self.pdv_a, taux=Decimal("2750"), user=self.admin)

        self.assertEqual(convertir_prix_usd_en_cdf("2.50", self.pdv_a), Decimal("6875.00"))
        self.assertEqual(convertir_prix_usd_en_cdf("2.50", self.pdv_b), Decimal("6500.00"))
        with self.assertRaises(TauxNonConfigureError):
            convertir_prix_usd_en_cdf("2.50", self.pdv_c)

    def test_global_mode_converts_all_prices_with_only_the_global_rate(self):
        """Le mode general ignore les regles ciblees lors du calcul du prix."""

        enregistrer_configuration(
            mode=ConfigurationTaux.MODE_GLOBAL,
            taux_global=Decimal("2500"),
            user=self.admin,
        )
        enregistrer_regle(point_de_vente=self.pdv_a, taux=Decimal("2900"), user=self.admin)

        self.assertEqual(convertir_prix_usd_en_cdf("2.50", self.pdv_a), Decimal("6250.00"))
        self.assertEqual(convertir_prix_usd_en_cdf("2.50", self.pdv_c), Decimal("6250.00"))

    def test_future_point_inherits_mention_rate(self):
        enregistrer_configuration(mode=ConfigurationTaux.MODE_PAR_CIBLE, taux_global=2400, user=self.admin)
        enregistrer_regle(mention=self.mention, taux=2650, user=self.admin)
        future = PointDeVente.objects.create(nom="Magasin futur")
        ParametrePointDeVente.objects.create(point_de_vente=future, mention=self.mention)
        self.assertEqual(taux_pour_point_de_vente(future), Decimal("2650"))

    def test_admin_screen_saves_rules_and_change_history(self):
        self.client.force_login(self.global_admin)
        response = self.client.post(reverse("g_taux:gestion"), data={
            "action": "configuration", "mode": ConfigurationTaux.MODE_PAR_CIBLE,
            "taux_global": "2450",
        }, follow=True)
        self.assertEqual(response.status_code, 200)
        response = self.client.post(reverse("g_taux:gestion"), data={
            "action": "regle", "type_cible": "mention", "mention": self.mention.pk,
            "point_de_vente": "", "taux": "2650", "actif": "on",
        }, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(RegleTaux.objects.get(mention=self.mention).taux, Decimal("2650"))
        self.assertEqual(HistoriqueTaux.objects.count(), 2)
        self.assertContains(response, "Magasin A")
        self.assertContains(response, "2650")

    def test_switching_to_target_mode_does_not_require_or_use_global_rate(self):
        enregistrer_configuration(
            mode=ConfigurationTaux.MODE_GLOBAL,
            taux_global=Decimal("2450"),
            user=self.global_admin,
        )
        self.client.force_login(self.global_admin)

        response = self.client.post(reverse("g_taux:gestion"), data={
            "action": "configuration",
            "mode": ConfigurationTaux.MODE_PAR_CIBLE,
        })

        self.assertEqual(response.status_code, 302)
        module_config = ConfigurationTaux.objects.get()
        self.assertEqual(module_config.mode, ConfigurationTaux.MODE_PAR_CIBLE)
        self.assertEqual(module_config.taux_global, Decimal("2450"))
        self.assertIsNone(resoudre_taux(self.pdv_a).taux)

    def test_management_screen_uses_modals_and_links_to_paginated_lists(self):
        self.client.force_login(self.global_admin)

        response = self.client.get(reverse("g_taux:gestion"))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'data-bs-target="#generalRateModal"')
        self.assertContains(response, 'data-bs-target="#targetRateModal"')
        self.assertContains(response, reverse("g_taux:taux-effectifs"))
        self.assertContains(response, reverse("g_taux:historique-utilise"))
        self.assertContains(response, "gestion_taux.js")
        self.assertContains(response, "Mode général : un taux unique")
        self.assertContains(response, "Taux par cible : point de vente ou mention")

    def test_rate_module_is_visible_near_configuration_in_admin_sidebar(self):
        """Le module métier doit être trouvable sans parcourir le bas du menu."""

        self.client.force_login(self.default_admin)

        response = self.client.get(reverse("g_taux:gestion"))

        administration = next(
            section
            for section in response.context["sidebar_sections"]
            if section["key"] == "administration"
        )
        menu_keys = [item["key"] for item in administration["items"]]
        self.assertEqual(
            menu_keys.index("g_taux"),
            menu_keys.index("configuration") + 1,
        )
        rate_item = next(item for item in administration["items"] if item["key"] == "g_taux")
        self.assertEqual(rate_item["url"], reverse("g_taux:gestion"))
        self.assertTrue(rate_item["is_active"])
        self.assertTrue(administration["is_active"])
        self.assertContains(response, "Gestion des taux")

    def test_admin_interface_applies_a_distinct_rate_to_each_point_of_sale(self):
        """Deux règles saisies dans l'interface restent propres à leur PDV."""

        self.client.force_login(self.global_admin)
        configuration_response = self.client.post(reverse("g_taux:gestion"), data={
            "action": "configuration",
            "mode": ConfigurationTaux.MODE_PAR_CIBLE,
            "taux_global": "2400",
        })
        self.assertRedirects(configuration_response, reverse("g_taux:gestion"))

        for point, rate in ((self.pdv_a, "2510"), (self.pdv_b, "2875")):
            rule_response = self.client.post(reverse("g_taux:gestion"), data={
                "action": "regle",
                "type_cible": "point",
                "point_de_vente": point.pk,
                "mention": "",
                "taux": rate,
                "actif": "on",
            })
            self.assertRedirects(rule_response, reverse("g_taux:gestion"))

        self.assertEqual(taux_pour_point_de_vente(self.pdv_a), Decimal("2510"))
        self.assertEqual(taux_pour_point_de_vente(self.pdv_b), Decimal("2875"))
        self.assertIsNone(resoudre_taux(self.pdv_c).taux)

        effective_rates = self.client.get(reverse("g_taux:taux-effectifs"))
        rows_by_point = {
            row["point"].pk: row["resolution"]
            for row in effective_rates.context["rows"]
        }
        self.assertEqual(rows_by_point[self.pdv_a.pk].taux, Decimal("2510"))
        self.assertEqual(rows_by_point[self.pdv_a.pk].source, "point_de_vente")
        self.assertEqual(rows_by_point[self.pdv_b.pk].taux, Decimal("2875"))
        self.assertEqual(rows_by_point[self.pdv_b.pk].source, "point_de_vente")

    def test_effective_rates_list_searches_and_paginates_only_accessible_points(self):
        for index in range(25):
            point = PointDeVente.objects.create(nom=f"Point taux {index:02d}")
            self.global_admin.points_de_vente.add(point)
        hidden = PointDeVente.objects.create(nom="Point taux caché")
        self.client.force_login(self.global_admin)

        response = self.client.get(reverse("g_taux:taux-effectifs"))

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context["page_obj"].paginator.count, 28)
        self.assertEqual(response.context["page_obj"].paginator.num_pages, 2)
        self.assertContains(response, 'id="effective-rate-search"')
        self.assertNotContains(response, hidden.nom)

        filtered = self.client.get(reverse("g_taux:taux-effectifs"), {"q": "Supermarché C"})
        self.assertEqual(filtered.context["page_obj"].paginator.count, 1)
        self.assertContains(filtered, "Supermarché C")
        self.assertNotContains(filtered, "Magasin A")

    def test_used_rate_history_is_a_searchable_paginated_permission_page(self):
        for index in range(27):
            Commande.objects.create(
                point_de_vente=self.pdv_a,
                vendeur=self.seller,
                client=self.customer,
                taux_change_applique=Decimal(2500 + index),
                montant_total=Decimal(5000 + index),
                type_facture="FV",
            )
        self.client.force_login(self.admin)

        response = self.client.get(reverse("g_taux:historique-utilise"))

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context["page_obj"].paginator.count, 27)
        self.assertEqual(response.context["page_obj"].paginator.num_pages, 2)
        self.assertContains(response, 'id="used-rate-search"')

        filtered = self.client.get(reverse("g_taux:historique-utilise"), {"q": "2526"})
        self.assertEqual(filtered.context["page_obj"].paginator.count, 1)
        self.assertContains(filtered, "2526")

        self.client.force_login(self.seller)
        UserMenuPermission.objects.create(user=self.seller, permission_key="g_taux", is_allowed=True)
        denied = self.client.get(reverse("g_taux:historique-utilise"))
        self.assertEqual(denied.status_code, 403)

    def test_scoped_admin_only_sees_and_updates_assigned_point(self):
        enregistrer_configuration(
            mode=ConfigurationTaux.MODE_PAR_CIBLE,
            taux_global=Decimal("2400"),
            user=self.global_admin,
        )
        self.client.force_login(self.admin)

        response = self.client.get(reverse("g_taux:gestion"))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Magasin A")
        self.assertNotContains(response, "Magasin B")
        self.assertNotContains(response, "Supermarché C")
        self.assertFalse(response.context["can_manage_all_rates"])
        self.assertNotContains(response, 'name="mode"')
        self.assertQuerySetEqual(
            response.context["rule_form"].fields["point_de_vente"].queryset,
            [self.pdv_a],
        )
        self.assertFalse(response.context["rule_form"].fields["mention"].queryset.exists())

        forbidden_point = self.client.post(reverse("g_taux:gestion"), data={
            "action": "regle", "type_cible": "point",
            "point_de_vente": self.pdv_b.pk, "mention": "",
            "taux": "2700", "actif": "on",
        })
        self.assertEqual(forbidden_point.status_code, 200)
        self.assertFalse(RegleTaux.objects.filter(point_de_vente=self.pdv_b).exists())

        forbidden_global = self.client.post(reverse("g_taux:gestion"), data={
            "action": "configuration", "mode": ConfigurationTaux.MODE_GLOBAL,
            "taux_global": "3000",
        })
        self.assertEqual(forbidden_global.status_code, 302)
        self.assertEqual(ConfigurationTaux.objects.get().taux_global, Decimal("2400"))

        allowed_point = self.client.post(reverse("g_taux:gestion"), data={
            "action": "regle", "type_cible": "point",
            "point_de_vente": self.pdv_a.pk, "mention": "",
            "taux": "2715", "actif": "on",
        })
        self.assertEqual(allowed_point.status_code, 302)
        self.assertEqual(
            RegleTaux.objects.get(point_de_vente=self.pdv_a).taux,
            Decimal("2715"),
        )

    def test_default_admin_sees_four_options_and_can_update_all_rates(self):
        self.client.force_login(self.default_admin)

        response = self.client.get(reverse("g_taux:gestion"))

        self.assertEqual(response.status_code, 200)
        self.assertTrue(response.context["can_manage_all_rates"])
        self.assertContains(response, 'class="rate-action-card', count=4)
        self.assertContains(response, 'data-bs-target="#generalRateModal"')
        self.assertQuerySetEqual(
            response.context["rule_form"].fields["point_de_vente"].queryset,
            [self.pdv_a, self.pdv_b, self.pdv_c],
        )

        configuration_response = self.client.post(reverse("g_taux:gestion"), data={
            "action": "configuration", "mode": ConfigurationTaux.MODE_GLOBAL,
            "taux_global": "3000",
        })
        self.assertEqual(configuration_response.status_code, 302)
        self.assertEqual(ConfigurationTaux.objects.get().taux_global, Decimal("3000"))

        rule_response = self.client.post(reverse("g_taux:gestion"), data={
            "action": "regle", "type_cible": "point",
            "point_de_vente": self.pdv_c.pk, "mention": "",
            "taux": "2850", "actif": "on",
        })
        self.assertEqual(rule_response.status_code, 302)
        self.assertEqual(
            RegleTaux.objects.get(point_de_vente=self.pdv_c).taux,
            Decimal("2850"),
        )

    def test_point_assigned_through_point_manager_is_in_admin_scope(self):
        self.pdv_b.assigned_admin = self.admin
        self.pdv_b.save(update_fields=["assigned_admin"])
        self.client.force_login(self.admin)

        response = self.client.get(reverse("g_taux:gestion"))

        self.assertEqual(response.status_code, 200)
        point_ids = set(
            response.context["rule_form"].fields["point_de_vente"].queryset.values_list("pk", flat=True)
        )
        self.assertEqual(point_ids, {self.pdv_a.pk, self.pdv_b.pk})
        self.assertContains(response, "Magasin B")
        self.assertNotContains(response, "Supermarché C")

    def test_dynamic_permissions_limit_access_and_allow_explicit_read(self):
        self.client.force_login(self.seller)
        denied = self.client.get(reverse("g_taux:gestion"))
        self.assertNotEqual(denied.status_code, 200)
        UserMenuPermission.objects.create(user=self.seller, permission_key="g_taux", is_allowed=True)
        UserMenuPermission.objects.create(user=self.seller, permission_key="g_taux_history", is_allowed=True)
        if hasattr(self.seller, "_cached_pos_permission_map"):
            del self.seller._cached_pos_permission_map
        allowed = self.client.get(reverse("g_taux:gestion"))
        self.assertEqual(allowed.status_code, 200)
        self.assertContains(allowed, reverse("g_taux:taux-effectifs"))
        effective = self.client.get(reverse("g_taux:taux-effectifs"))
        self.assertContains(effective, "Magasin A")
        self.assertNotContains(effective, "Supermarché C")

    def test_management_screen_is_translated_in_english(self):
        self.client.force_login(self.admin)
        response = self.client.get(
            reverse("g_taux:gestion"),
            HTTP_ACCEPT_LANGUAGE="en",
        )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Centralized exchange rates")
        self.assertContains(response, "Rate change log")
        self.assertContains(response, "Effective rates by group and point of sale")
        self.assertContains(response, "Open effective rates list")

        effective = self.client.get(
            reverse("g_taux:taux-effectifs"),
            HTTP_ACCEPT_LANGUAGE="en",
        )
        self.assertContains(effective, "Search effective rates")
        self.assertContains(effective, "Point of sale, group, source or rate")

        history = self.client.get(
            reverse("g_taux:historique-utilise"),
            HTTP_ACCEPT_LANGUAGE="en",
        )
        self.assertContains(history, "History of rates actually used")
        self.assertContains(history, "Period, point of sale, rate or amount")

    def test_pos_sale_uses_and_freezes_effective_point_rate(self):
        enregistrer_configuration(mode=ConfigurationTaux.MODE_PAR_CIBLE, taux_global=2400, user=self.admin)
        enregistrer_regle(point_de_vente=self.pdv_a, taux=Decimal("2750"), user=self.admin)
        self.client.force_login(self.seller)
        with patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            return_value={"success": True, "channel": "MCF", "commande_id": 1, "fiscal_transaction_id": "rate-test"},
        ):
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps({
                    "panier": [{"id": self.product.pk, "conditionnement_id": self.packaging.pk, "qty": 2}],
                    "client_id": self.customer.pk,
                }),
                content_type="application/json",
            )
        self.assertEqual(response.status_code, 200, response.content)
        commande = Commande.objects.get(pk=response.json()["commande_id"])
        self.assertEqual(commande.taux_change_applique, Decimal("2750"))
        self.assertEqual(commande.lignes.get().prix_unitaire, Decimal("2750"))

    def test_pos_sale_uses_the_modified_price_at_the_rate_of_the_point(self):
        """Le prix modifié arrive sur la facture, au taux du point de vente."""

        enregistrer_configuration(mode=ConfigurationTaux.MODE_PAR_CIBLE, taux_global=2400, user=self.admin)
        enregistrer_regle(point_de_vente=self.pdv_a, taux=Decimal("2750"), user=self.admin)
        ProduitPointVentePrix.objects.create(
            produit=self.product, conditionnement=self.packaging, point_de_vente=self.pdv_a, prix_vente=Decimal("1"),
        )
        self.packaging.prix_vente = Decimal("2")
        self.packaging.save()
        enregistrer_changement_prix_standard(self.packaging, Decimal("1"), "test", self.admin)
        self.client.force_login(self.seller)

        with patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            return_value={"success": True, "channel": "MCF", "commande_id": 1, "fiscal_transaction_id": "price-test"},
        ):
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps({
                    "panier": [{"id": self.product.pk, "conditionnement_id": self.packaging.pk, "qty": 1}],
                    "client_id": self.customer.pk,
                }),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200, response.content)
        commande = Commande.objects.get(pk=response.json()["commande_id"])
        self.assertEqual(commande.taux_change_applique, Decimal("2750"))
        self.assertEqual(commande.lignes.get().prix_unitaire, Decimal("5500"))

    def test_pos_sale_uses_mention_rate_in_target_mode(self):
        """Une vente sans regle PDV applique le taux de sa mention."""

        enregistrer_configuration(
            mode=ConfigurationTaux.MODE_PAR_CIBLE,
            taux_global=Decimal("2400"),
            user=self.admin,
        )
        enregistrer_regle(mention=self.mention, taux=Decimal("2625"), user=self.admin)
        self.seller.point_de_vente = self.pdv_b
        self.seller.save(update_fields=["point_de_vente"])
        StockPointDeVente.objects.create(
            point_de_vente=self.pdv_b,
            produit=self.product,
            quantite=Decimal("20"),
        )
        self.client.force_login(self.seller)

        with patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            return_value={
                "success": True,
                "channel": "MCF",
                "commande_id": 1,
                "fiscal_transaction_id": "mention-rate-test",
            },
        ):
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps({
                    "panier": [{
                        "id": self.product.pk,
                        "conditionnement_id": self.packaging.pk,
                        "qty": 2,
                    }],
                    "client_id": self.customer.pk,
                }),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200, response.content)
        commande = Commande.objects.get(pk=response.json()["commande_id"])
        self.assertEqual(commande.taux_change_applique, Decimal("2625"))
        self.assertEqual(commande.lignes.get().prix_unitaire, Decimal("2625"))

    def test_pos_sale_is_blocked_when_target_mode_has_no_rate_for_point(self):
        enregistrer_configuration(
            mode=ConfigurationTaux.MODE_PAR_CIBLE,
            taux_global=Decimal("2400"),
            user=self.admin,
        )
        self.seller.point_de_vente = self.pdv_c
        self.seller.save(update_fields=["point_de_vente"])
        self.client.force_login(self.seller)

        response = self.client.post(
            reverse("facturation:pos-view"),
            data=json.dumps({
                "panier": [{
                    "id": self.product.pk,
                    "conditionnement_id": self.packaging.pk,
                    "qty": 1,
                }],
                "client_id": self.customer.pk,
            }),
            content_type="application/json",
        )

        self.assertEqual(response.status_code, 409)
        self.assertIn("Aucun taux configuré", response.json()["error"])
        self.assertFalse(Commande.objects.exists())

    def test_mobile_login_reports_missing_target_rate_without_server_error(self):
        enregistrer_configuration(
            mode=ConfigurationTaux.MODE_PAR_CIBLE,
            taux_global=Decimal("2400"),
            user=self.admin,
        )
        self.seller.point_de_vente = self.pdv_c
        self.seller.save(update_fields=["point_de_vente"])

        response = self.client.post("/api/auth/login/", data={
            "email": self.seller.email,
            "password": "secret",
        })

        self.assertEqual(response.status_code, 200, response.content)
        self.assertIsNone(response.json()["taux_change"])
        self.assertEqual(response.json()["taux_change_source"], "non_configure")
        self.assertIn("Aucun taux configuré", response.json()["taux_change_error"])

    def test_mobile_catalogue_is_blocked_without_target_rate(self):
        enregistrer_configuration(
            mode=ConfigurationTaux.MODE_PAR_CIBLE,
            taux_global=Decimal("2400"),
            user=self.admin,
        )
        self.seller.point_de_vente = self.pdv_c
        self.seller.save(update_fields=["point_de_vente"])
        self.client.force_login(self.seller)

        response = self.client.get("/api/produits/sync/")

        self.assertEqual(response.status_code, 409, response.content)
        self.assertIn("Aucun taux configuré", response.json()["error"])

    def test_fiscal_payload_uses_frozen_invoice_rate_not_current_global_rate(self):
        commande = Commande.objects.create(
            point_de_vente=self.pdv_a, vendeur=self.seller, client=self.customer,
            taux_change_applique=Decimal("2675"), montant_total=Decimal("2675"),
        )
        LigneCommande.objects.create(
            commande=commande, produit=self.product, conditionnement=self.packaging,
            quantite=1, prix_unitaire=2675, sous_total=2675,
        )
        self.config.taux_change = Decimal("3000")
        self.config.save(update_fields=["taux_change"])
        payload = FiscalPayloadBuilder().build(commande)
        self.assertEqual(payload["company"]["currency_rate"], Decimal("2675"))
        self.assertEqual(payload["company"]["currency_code"], "CDF")
        dgi_payload = EmcfAdapter()._build_request_payload(payload)
        self.assertNotIn("curCode", dgi_payload)
        self.assertNotIn("curRate", dgi_payload)
        self.assertNotIn("curDate", dgi_payload)

    def test_proforma_creation_uses_effective_rate(self):
        enregistrer_configuration(mode=ConfigurationTaux.MODE_PAR_CIBLE, taux_global=2400, user=self.admin)
        enregistrer_regle(point_de_vente=self.pdv_a, taux=Decimal("2725"), user=self.admin)
        proforma = ProformaCreationService().create_from_payload(self.seller, {
            "panier": [{"id": self.product.pk, "qty": 1}],
            "client_id": self.customer.pk,
            "document_mode": "FV",
        })
        self.assertEqual(proforma.taux_change_applique, Decimal("2725"))
        self.assertEqual(proforma.lignes.get().prix_unitaire, Decimal("2725"))

    def test_mobile_sale_uses_and_freezes_effective_rate(self):
        enregistrer_configuration(mode=ConfigurationTaux.MODE_PAR_CIBLE, taux_global=2400, user=self.admin)
        enregistrer_regle(point_de_vente=self.pdv_a, taux=Decimal("2710"), user=self.admin)
        serializer = POSSaleSerializer(
            data={
                "lignes": [{
                    "product_id": self.product.pk,
                    "conditionnement_id": self.packaging.pk,
                    "qty": 1,
                }],
                "paiement": {"montant_verse": 2710, "devise": "USD", "mode": "ESPECES"},
            },
            context={"request": SimpleNamespace(user=self.seller)},
        )
        self.assertTrue(serializer.is_valid(), serializer.errors)

        commande = serializer.save()

        self.assertEqual(commande.taux_change_applique, Decimal("2710"))
        self.assertEqual(commande.lignes.get().prix_unitaire, Decimal("2710"))
        self.assertEqual(commande.paiements.get().taux_transaction, Decimal("2710"))

    def test_week_month_year_usage_history_uses_frozen_rates(self):
        Commande.objects.create(
            point_de_vente=self.pdv_a, vendeur=self.seller, client=self.customer,
            taux_change_applique=Decimal("2550"), montant_total=Decimal("5100"), type_facture="FV",
        )
        self.client.force_login(self.admin)
        for grouping in ("semaine", "mois", "annee"):
            with self.subTest(grouping=grouping):
                response = self.client.get(reverse("g_taux:historique-utilise"), {"regroupement": grouping})
                self.assertEqual(response.status_code, 200)
                rows = response.context["rows"]
                self.assertTrue(any(row["taux_change_applique"] == Decimal("2550") for row in rows))
