"""Contrat de recherche commun : pertinence, bornes, droits et contextes métier."""
from decimal import Decimal
from unittest.mock import patch

from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.db import connection
from django.test import TestCase
from django.test.utils import CaptureQueriesContext
from django.urls import reverse

from achats.forms import AchatForm, LigneAchatForm
from achats.models import Achat, LigneAchat, ReceptionAchat, LigneReceptionAchat
from fournisseurs.models import Fournisseur
from stock.models_inventaires import InventaireStock, LigneInventaireStock
from .models import Client, ConditionnementProduit, ModePaiement, PointDeVente, Produit, StockPointDeVente, UserMenuPermission


class FacControlSearchTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.pdv = PointDeVente.objects.create(nom="Gombe")
        cls.other = PointDeVente.objects.create(nom="Autre dépôt")
        cls.user = get_user_model().objects.create_user(username="search-admin", email="search@example.com", role="ADMIN", point_de_vente=cls.pdv)
        cls.vendor = get_user_model().objects.create_user(username="search-vendor", email="vendor-search@example.com", role="VENDEUR", point_de_vente=cls.pdv)
        cls.product = Produit.objects.create(nom="École Jean Pierre", code_sku="ART01", prix_vente=1000)
        cls.stock = StockPointDeVente.objects.create(produit=cls.product, point_de_vente=cls.pdv, quantite=37)
        StockPointDeVente.objects.create(produit=cls.product, point_de_vente=cls.other, quantite=98)
        cls.customer = Client.objects.create(nom_complet="École Jean Pierre", nif="NIF-CLIENT-01", telephone="0991234567")
        cls.supplier = Fournisseur.objects.create(raison_sociale="École Jean Pierre", nif="NIF-FOU-01", telephone="0997654321")
        cls.purchase = Achat.objects.create(fournisseur=cls.supplier, point_de_vente=cls.pdv, reference_fournisseur="FAC-4587", created_by=cls.user)
        cls.foreign_purchase = Achat.objects.create(fournisseur=cls.supplier, point_de_vente=cls.other)

    def setUp(self):
        cache.clear()
        self.client.force_login(self.user)
        self.url = reverse("facturation:search")

    def search(self, entity, context, q, **params):
        response = self.client.get(self.url, {"entity":entity, "context":context, "q":q, **params})
        self.assertEqual(response.status_code, 200, response.content[:500])
        return response.json()["results"]

    def test_exact_partial_case_and_accents_for_all_required_entities(self):
        for entity, scope, obj, identifiers in (
            ("product", "purchase", self.product, ("ART01", "art0", "Pierre", "ecole", "ÉCOLE")),
            ("client", "clients", self.customer, ("École Jean Pierre", "PIERRE", "ecole", "NIF-CLIENT", "099123")),
            ("supplier", "suppliers", self.supplier, (self.supplier.code.lower(), "PIERRE", "ecole", "NIF-FOU", "099765")),
            ("purchase", "purchases", self.purchase, (self.purchase.numero.lower(), "FAC-4587", "fac-45", "PIERRE", "ecole")),
        ):
            for query in identifiers:
                with self.subTest(entity=entity, query=query):
                    self.assertIn(obj.pk, [row["id"] for row in self.search(entity, scope, query)])

    def test_ranking_product_exact_prefix_name_then_contains(self):
        prefix = Produit.objects.create(prix_vente=1000,nom="Autre", code_sku="ART01-EXT")
        exact_name = Produit.objects.create(prix_vente=1000,nom="ART01", code_sku="ZZ-01")
        name_prefix = Produit.objects.create(prix_vente=1000,nom="ART01 complément", code_sku="ZZ-02")
        contains = Produit.objects.create(prix_vente=1000,nom="Le produit ART01 final", code_sku="ZZ-03")
        self.assertEqual([row["id"] for row in self.search("product", "purchase", "art01")],
                         [self.product.pk, prefix.pk, exact_name.pk, name_prefix.pk, contains.pk])

    def test_ranking_supplier_and_purchase_identifiers_precede_names(self):
        same_name = Fournisseur.objects.create(raison_sociale=self.supplier.code)
        rows = self.search("supplier", "suppliers", self.supplier.code)
        self.assertEqual([r["id"] for r in rows], [self.supplier.pk, same_name.pk])
        self.supplier.raison_sociale = self.purchase.numero
        self.supplier.save()
        self.assertEqual(self.search("purchase", "purchases", self.purchase.numero)[0]["id"], self.purchase.pk)

    def test_limit_and_single_character_queries_are_bounded(self):
        for index in range(25):
            Produit.objects.create(prix_vente=1000,nom=f"Alpha {index:02}", code_sku=f"LIMIT-{index:02}")
            Client.objects.create(nom_complet=f"Alpha {index:02}")
            Fournisseur.objects.create(raison_sociale=f"Alpha {index:02}")
            Achat.objects.create(fournisseur=self.supplier, point_de_vente=self.pdv, reference_fournisseur=f"Alpha {index:02}")
        for entity, scope in (("product","purchase"), ("client","clients"), ("supplier","suppliers"), ("purchase","purchases")):
            self.assertEqual(len(self.search(entity, scope, "a", limit=999)), 20)
            self.assertEqual(len(self.search(entity, scope, "a", limit=3)), 3)

    def test_empty_errors_and_unauthenticated_access(self):
        self.assertEqual(self.search("product", "purchase", ""), [])
        self.assertEqual(self.search("supplier", "suppliers", "introuvable"), [])
        self.assertEqual(self.client.get(self.url, {"entity":"unknown", "context":"purchase"}).status_code, 400)
        self.assertEqual(self.client.get(self.url, {"entity":"supplier", "context":"pos"}).status_code, 400)
        self.client.logout()
        self.assertEqual(self.client.get(self.url, {"entity":"product", "context":"purchase", "q":"a"}).status_code, 302)

    def test_permissions_are_required_for_each_endpoint(self):
        self.client.force_login(self.vendor)
        for entity, scope in (("product","purchase"), ("client","clients"), ("supplier","suppliers"), ("purchase","purchases")):
            UserMenuPermission.objects.update_or_create(user=self.vendor, permission_key={"purchase":"achats_create", "clients":"clients", "suppliers":"fournisseurs", "purchases":"achats"}[scope], defaults={"is_allowed":False})
            cache.clear()
            response = self.client.get(self.url, {"entity":entity,"context":scope,"q":"a"})
            self.assertEqual(response.status_code,403)

    def test_purchase_and_pdv_scope_cannot_be_bypassed_by_id(self):
        self.client.force_login(self.vendor)
        UserMenuPermission.objects.create(user=self.vendor,permission_key="achats",is_allowed=True)
        cache.clear()
        self.assertEqual(self.search("purchase", "purchases", "", id=self.foreign_purchase.pk), [])
        self.assertEqual(self.client.get(self.url,{"entity":"purchase","context":"purchases","q":"a","pdv":self.other.pk}).status_code,404)
        self.assertEqual([o["id"] for o in self.search("purchase","purchases",self.purchase.numero)], [self.purchase.pk])

    def test_product_catalogue_scope_matches_existing_list(self):
        foreign = Produit.objects.create(prix_vente=1000,nom="École secrète",code_sku="FOREIGN")
        StockPointDeVente.objects.create(produit=foreign,point_de_vente=self.other,quantite=12)
        self.client.force_login(self.vendor)
        UserMenuPermission.objects.create(user=self.vendor,permission_key="produits",is_allowed=True)
        cache.clear()
        self.assertEqual([r["id"] for r in self.search("product","catalogue","ecole")],[self.product.pk])
        self.assertEqual(self.search("product","catalogue","",id=foreign.pk),[])

    def test_purchase_packagings_are_active_and_purchasable_only(self):
        excluded = ConditionnementProduit.objects.create(prix_vente=1000,produit=self.product,code="SALE",libelle="Vente",facteur_conversion=6,achetable=False)
        inactive = ConditionnementProduit.objects.create(prix_vente=1000,produit=self.product,code="OLD",libelle="Ancien",facteur_conversion=12,actif=False)
        result = self.search("product","purchase","ART01")[0]
        self.assertNotIn(excluded.pk,[p["id"] for p in result["packagings"]])
        self.assertNotIn(inactive.pk,[p["id"] for p in result["packagings"]])
        self.assertIn(excluded.pk,[p["id"] for p in self.search("product","direct","ART01",pdv=self.pdv.pk)[0]["packagings"]])

    def test_transfer_returns_real_source_stock_and_requires_source(self):
        self.assertEqual(self.search("product","transfer","ART01"),[])
        self.assertEqual(Decimal(self.search("product","transfer","ART01",pdv=self.pdv.pk)[0]["stock"]),37)
        self.assertEqual(Decimal(self.search("product","transfer","ART01",pdv=self.other.pk)[0]["stock"]),98)

    def test_blind_inventory_never_serializes_theoretical_stock(self):
        inventory = InventaireStock.objects.create(point_de_vente=self.pdv,created_by=self.user,type_inventaire="PARTIEL",masquer_theorique=True)
        rows = self.search("product","inventory","ART01",inventory=inventory.pk)
        self.assertNotIn("stock",rows[0])
        self.assertNotIn("37", str(rows[0]["columns"]))
        inventory = InventaireStock.objects.create(point_de_vente=self.pdv,created_by=self.user,type_inventaire="PARTIEL",masquer_theorique=False)
        self.assertIn("stock",self.search("product","inventory","ART01",inventory=inventory.pk)[0])
        self.client.force_login(self.vendor)
        UserMenuPermission.objects.create(user=self.vendor,permission_key="inventaires_count",is_allowed=True)
        UserMenuPermission.objects.create(user=self.vendor,permission_key="inventaires_theoretical",is_allowed=False)
        cache.clear()
        self.assertNotIn("stock",self.search("product","inventory","ART01",inventory=inventory.pk)[0])

    def test_inventory_excludes_products_already_added(self):
        inventory=InventaireStock.objects.create(point_de_vente=self.pdv,created_by=self.user,type_inventaire="PARTIEL")
        LigneInventaireStock.objects.create(inventaire=inventory,produit=self.product)
        self.assertEqual(self.search("product","inventory","ART01",inventory=inventory.pk),[])

    def test_widgets_do_not_render_all_entities_and_keep_model_validation(self):
        for index in range(35):
            Produit.objects.create(prix_vente=1000,nom=f"Invisible DOM {index}",code_sku=f"DOM-{index}")
            Fournisseur.objects.create(raison_sociale=f"Invisible DOM {index}")
        header=AchatForm(user=self.user)
        line=LigneAchatForm()
        self.assertNotIn("Invisible DOM",str(header["fournisseur"]))
        self.assertNotIn("Invisible DOM",str(line["produit"]))
        self.assertIn('data-faccontrol-search="product"',str(line["produit"]))
        bound=LigneAchatForm(instance=LigneAchat(achat=self.purchase),data={"produit":self.product.pk,"conditionnement":self.product.conditionnements.get().pk,"quantite":1,"prix_achat_conditionnement":100,"remise":0})
        self.assertTrue(bound.is_valid(),bound.errors)
        self.assertIn('selected',str(bound["produit"]))
        bound=LigneAchatForm(instance=LigneAchat(achat=self.purchase),data={"produit":99999999})
        self.assertFalse(bound.is_valid())
        # Un ID malformé reste une erreur de formulaire, sans provoquer un
        # dépassement SQL pendant le rendu des seuls choix sélectionnés.
        for identifier in ("9" * 100, "²", "not-an-id"):
            header=AchatForm(user=self.user,data={"fournisseur":identifier})
            self.assertNotIn("Invisible DOM",str(header["fournisseur"]))
            self.assertEqual(self.search("supplier","suppliers","",id=identifier),[])

    def test_results_have_no_n_plus_one_for_product_packagings(self):
        for index in range(20):
            p=Produit.objects.create(prix_vente=1000,nom=f"Performant {index}",code_sku=f"PERF-{index}")
            StockPointDeVente.objects.create(produit=p,point_de_vente=self.pdv,quantite=1)
        # Chauffer les caches de menus, mesurer les deux tailles avec la même portée.
        self.search("product","direct","performant",pdv=self.pdv.pk)
        counts=[]
        for limit in (1,20):
            with CaptureQueriesContext(connection) as captured:
                self.search("product","direct","performant",pdv=self.pdv.pk,limit=limit)
            counts.append(len(captured))
        self.assertEqual(counts[0],counts[1])
        self.assertLessEqual(counts[1],12)

    def test_migrated_list_templates_render_with_authorized_filters(self):
        for route in ("facturation:retour-fournisseur-list", "facturation:achat-list", "facturation:transfert-stock-list", "facturation:inventaire-stock-list", "facturation:paiement-fournisseur-list", "facturation:reception-achat-list", "proforma:list"):
            with self.subTest(route=route):
                response = self.client.get(reverse(route))
                self.assertEqual(response.status_code, 200)

    def test_receipt_payment_and_return_search_use_real_documents_and_remaining_lots(self):
        from achats.models import RetourFournisseur, LigneRetourFournisseur
        from paiements.models import PaiementFournisseur
        pack=self.product.conditionnements.get()
        line=LigneAchat.objects.create(achat=self.purchase,produit=self.product,conditionnement=pack,quantite=10,prix_achat_conditionnement=100)
        self.purchase.valider()
        self.assertEqual(self.search("purchase","return",self.purchase.numero),[])
        reception=ReceptionAchat.objects.create(achat=self.purchase,point_de_vente=self.pdv,reference_bon_livraison="BL-SEARCH")
        source=LigneReceptionAchat.objects.create(reception=reception,ligne_achat=line,quantite_commerciale_recue=10)
        reception.valider(user=self.user)
        source.refresh_from_db()
        self.assertEqual(self.search("receipt","receipts","BL-SEARCH")[0]["id"],reception.pk)
        self.assertEqual(self.search("purchase","receipt",self.purchase.numero),[])
        self.assertEqual(self.search("purchase","return",self.purchase.numero)[0]["id"],self.purchase.pk)
        payment=PaiementFournisseur.objects.create(achat=self.purchase,montant=100,mode_paiement=ModePaiement.objects.get_or_create(code="ESPECES",defaults={"designation":"Espèces"})[0],reference_paiement="PAY-SEARCH")
        self.assertEqual(self.search("payment","payments","PAY-SEARCH")[0]["id"],payment.pk)
        result=self.search("return_line","return","ART01",purchase=self.purchase.pk)[0]
        self.assertEqual(Decimal(result["remaining"]),10)
        retour=RetourFournisseur.objects.create(achat=self.purchase,motif="DEFECTUEUX",reference_fournisseur="RETURN-SEARCH")
        LigneRetourFournisseur.objects.create(retour=retour,ligne_reception=source,quantite_commerciale=10)
        retour.valider(user=self.user)
        self.assertEqual(self.search("return","returns","ART01")[0]["id"],retour.pk)
        self.assertEqual(self.search("return_line","return","",id=source.pk,purchase=self.purchase.pk),[])
        self.assertEqual(self.search("purchase","return",self.purchase.numero),[])

    def test_many_pdv_preserve_multiple_widget_and_selected_real_ids(self):
        from facturation.forms import ProduitExcelExportForm
        from facturation.search_widgets import SearchSelectMultiple
        for index in range(25):PointDeVente.objects.create(nom=f"Large point {index}")
        form=ProduitExcelExportForm(user=self.user)
        self.assertIsInstance(form.fields["points_de_vente"].widget,SearchSelectMultiple)
        self.assertNotIn("Large point",str(form["points_de_vente"]))
        self.assertTrue(form.fields["points_de_vente"].widget.allow_multiple_selected)
        self.assertEqual(self.search("product","catalogue","ART01",pdv="all")[0]["id"],self.product.pk)

    def test_point_choices_open_without_a_query_and_keep_limit_and_scope(self):
        for index in range(25): PointDeVente.objects.create(nom=f"Point dropdown {index:02}")
        results=self.search("pdv","catalogue","",limit=3)
        self.assertEqual([item['id'] for item in results],list(PointDeVente.objects.order_by('nom','pk').values_list('pk',flat=True)[:3]))
        self.client.force_login(self.vendor)
        UserMenuPermission.objects.update_or_create(user=self.vendor,permission_key='stocks',defaults={'is_allowed':True})
        cache.clear()
        self.assertEqual([item['id'] for item in self.search('pdv','stock','')],[self.pdv.pk])
        self.assertEqual(self.search('pdv','stock','',id=self.other.pk),[])
        UserMenuPermission.objects.update_or_create(user=self.vendor,permission_key='backup_ventes',defaults={'is_allowed':False})
        cache.clear()
        self.assertEqual(self.client.get(self.url,{'entity':'pdv','context':'backup','q':''}).status_code,403)

    def test_small_point_choices_use_the_shared_selector_and_keep_model_validation(self):
        from .search_widgets import SearchSelectMultiple
        form=AchatForm(user=self.user)
        self.assertIsInstance(form.fields['points_de_vente'].widget,SearchSelectMultiple)
        html=str(form['points_de_vente'])
        self.assertIn('data-faccontrol-search="pdv"',html)
        self.assertNotIn('Autre dépôt',html)
        self.assertIn('multiple',html)
        self.assertIn('tous_points_de_vente',form.fields)
        response=self.client.get(reverse('facturation:user-create'))
        self.assertContains(response,'data-faccontrol-search="pdv"')
        self.assertContains(response,'data-search-default-all="false"')

    def test_proforma_suggestions_and_list_keep_original_primary_point_scope(self):
        from proforma.models import Proforma
        self.client.force_login(self.vendor)
        UserMenuPermission.objects.update_or_create(user=self.vendor,permission_key="proformas",defaults={"is_allowed":True})
        self.vendor.points_de_vente.add(self.other)
        Proforma.objects.create(point_de_vente=self.pdv,vendeur=self.vendor,client=self.customer)
        foreign=Proforma.objects.create(point_de_vente=self.other,vendeur=self.vendor,client=self.customer)
        cache.clear()
        self.assertEqual(self.search("proforma","proforma","",id=foreign.pk),[])
        response=self.client.get(reverse("proforma:list"))
        self.assertEqual(response.context["paginator"].count,1)

    def test_visual_pos_loads_one_card_page_and_search_remains_bounded(self):
        for index in range(65):
            p=Produit.objects.create(nom=f"Visuel {index:02}",code_sku=f"VIS-{index:02}",prix_vente=1000)
            StockPointDeVente.objects.create(produit=p,point_de_vente=self.pdv,quantite=1)
        response=self.client.get(reverse("facturation:pos-view"),{"billing":"visual"})
        import json
        self.assertEqual(len(json.loads(response.context["produits_json"])),60)
        self.assertEqual(response.context["visual_next_offset"],60)
        data=self.client.get(reverse("facturation:pos-catalogue"),{"visual":"1","offset":60}).json()
        self.assertLessEqual(len(data["results"]),60)
        self.assertIsNone(data["next_offset"])
        suggestions=self.client.get(reverse("facturation:pos-catalogue"),{"visual":"1","q":"VIS-"}).json()["results"]
        self.assertEqual(len(suggestions),15)

    def test_stock_document_search_matches_real_references_and_scope(self):
        from stock.models import TransfertStock, ReapprovisionnementDirect
        transfer=TransfertStock.objects.create(point_de_vente_source=self.pdv,point_de_vente_destination=self.other,created_by=self.user,motif="Recherche")
        inventory=InventaireStock.objects.create(point_de_vente=self.pdv,created_by=self.user,type_inventaire="PARTIEL")
        direct=ReapprovisionnementDirect.objects.create(point_de_vente=self.pdv,created_by=self.user)
        for entity,scope,obj in (("transfer","transfers",transfer),("inventory","inventory_filter",inventory),("direct","direct_history",direct)):
            with self.subTest(entity=entity):
                self.assertEqual(self.search(entity,scope,obj.numero.lower())[0]["id"],obj.pk)
                self.assertEqual(self.search(entity,scope,"gombe")[0]["id"],obj.pk)
        response=self.client.get(reverse("facturation:stock-entry"),{"q":direct.numero})
        self.assertContains(response,direct.numero)
        self.client.force_login(self.vendor)
        for key in ("transferts","inventaires","stocks"):
            UserMenuPermission.objects.update_or_create(user=self.vendor,permission_key=key,defaults={"is_allowed":True})
        foreign=ReapprovisionnementDirect.objects.create(point_de_vente=self.other,created_by=self.user)
        cache.clear()
        self.assertEqual(self.search("direct","direct_history","",id=foreign.pk),[])
        # Un transfert doit être visible aux deux extrémités, comme sa liste actuelle.
        self.assertEqual(self.search("transfer","transfers","",id=transfer.pk),[])

    def test_large_admin_point_selector_keeps_empty_default_and_current_ids(self):
        for index in range(25):PointDeVente.objects.create(nom=f"Remote admin point {index}")
        response=self.client.get(reverse("facturation:user-create"))
        self.assertEqual(response.status_code,200)
        self.assertNotContains(response,"Remote admin point")
        self.assertContains(response,'data-search-default-all="false"')
        self.assertEqual(len(self.search("pdv","admin_user_form","Remote admin point",limit=3)),3)
        response=self.client.get(reverse("facturation:user-list"),{"q":"search-vendor"})
        self.assertEqual(response.context["paginator"].count,1)
        self.assertEqual(response.context["users"][0].pk,self.vendor.pk)

    def test_common_pagination_retains_entity_and_other_filters(self):
        from django.template import engines
        from django.test import RequestFactory
        from django.core.paginator import Paginator
        request=RequestFactory().get("/",{"q":"école","client":self.customer.pk,"pdv":[self.pdv.pk,self.other.pk]})
        template=engines["django"].get_template("facturation/search/pagination.html")
        html=template.render({"request":request,"page_obj":Paginator(range(35),30).page(1)})
        self.assertIn(f"client={self.customer.pk}",html)
        self.assertIn(f"pdv={self.pdv.pk}",html)
        self.assertIn(f"pdv={self.other.pk}",html)
        self.assertIn("page=2",html)

    def test_large_pos_references_render_only_the_selected_point_and_remote_categories(self):
        from .models import Categorie
        for index in range(25):
            PointDeVente.objects.create(nom=f"Remote POS point {index:02}")
            Categorie.objects.create(nom=f"Remote POS category {index:02}")
        response=self.client.get(reverse("facturation:pos-view"))
        self.assertNotContains(response,"Remote POS point")
        self.assertNotContains(response,"Remote POS category")
        self.assertContains(response,'data-faccontrol-search="pdv"')
        self.assertContains(response,'id="quickProductCategory" data-faccontrol-search="category"')
        self.assertEqual(len(self.search("pdv","pos","Remote POS point",limit=3)),3)
        created=self.client.post(reverse("facturation:produit-quick-category-create"),{"quick_category-nom":"Nouvelle catégorie distante","quick_category-description":""})
        self.assertEqual(created.status_code,200)
        self.assertEqual(len(created.json()["categories"]),1)
        self.assertEqual(created.json()["categories"][0]["id"],created.json()["categorie"]["id"])

    def test_direct_reference_uses_local_year_at_the_utc_year_boundary(self):
        from datetime import datetime, timezone as datetime_timezone
        from stock.models import ReapprovisionnementDirect
        document=ReapprovisionnementDirect.objects.create(point_de_vente=self.pdv,created_by=self.user)
        ReapprovisionnementDirect.objects.filter(pk=document.pk).update(created_at=datetime(2025,12,31,23,30,tzinfo=datetime_timezone.utc))
        document.refresh_from_db()
        self.assertIn("2026",document.numero)
        self.assertEqual(self.search("direct","direct_history",document.numero)[0]["id"],document.pk)
