"""Catalogue global, projections par PDV, performances et moteur POS partage."""
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 Client as TestClient, TestCase
from django.test.utils import CaptureQueriesContext
from django.urls import reverse

from dgi.models import TaxGroup
from .models import (
    Client, Commande, ConditionnementProduit, Configuration, LigneCommande,
    ModePaiement, MouvementStock, Paiement, PointDeVente, Produit,
    ProduitPointVentePrix, StockPointDeVente, UserMenuPermission,
)
from .pos_catalogue import build_pos_catalogue, pos_product_queryset, search_pos_products


class QuickBillingTests(TestCase):
    def setUp(self):
        cache.clear()
        self.pdv = PointDeVente.objects.create(nom="Caisse clavier")
        self.other_pdv = PointDeVente.objects.create(nom="Autre magasin")
        self.user = get_user_model().objects.create_user(
            username="quick-cashier", email="quick@example.com", role="VENDEUR", point_de_vente=self.pdv,
        )
        self.config = Configuration.objects.create(taux_change=1, mode_dgi="ht", type_dgi="FV", nif="A1234567Q", isf_dgi="CD01000000-1")
        self.group = TaxGroup.objects.create(code="QB", name="Taxable", tax=16)
        self.product = self.product_with_stock("PEMPASE", "GEDETEST01")
        self.piece = self.product.conditionnements.get()
        self.piece.libelle = "Pièce"
        self.piece.save()
        self.packet = ConditionnementProduit.objects.create(
            produit=self.product, code="PACK6", libelle="Paquet", facteur_conversion=6, prix_vente=5500,
        )
        self.carton = ConditionnementProduit.objects.create(
            produit=self.product, code="CARTON12", libelle="Carton", facteur_conversion=12, prix_vente=10000,
        )
        ProduitPointVentePrix.objects.create(produit=self.product, conditionnement=self.carton,
            point_de_vente=self.pdv, prix_vente=9000)
        self.customer = Client.objects.create(nom_complet="Client clavier", telephone="0991234567", nif="A1234567Q")
        ModePaiement.objects.update_or_create(code="ESPECES", defaults={"designation":"Espèces"})
        ModePaiement.objects.update_or_create(code="CARD", defaults={"designation":"Carte"})
        self.client.force_login(self.user)
        self.url = reverse("facturation:pos-catalogue")

    def tearDown(self):
        cache.clear()

    def product_with_stock(self, name, code, pdv=None, stock=100):
        product = Produit.objects.create(nom=name, code_sku=code, prix_vente=1000, taxgroup=self.group)
        StockPointDeVente.objects.create(produit=product, point_de_vente=pdv or self.pdv, quantite=stock)
        return product

    def test_quick_page_has_no_eager_catalogue_and_visual_remains_available(self):
        quick = self.client.get(reverse("facturation:pos-view"))
        self.assertEqual(quick.status_code, 200)
        self.assertTrue(quick.context["compact_sidebar"])
        self.assertContains(quick, 'class="theme-light pos-compact-sidebar"')
        self.assertEqual(quick.context["produits_json"], "[]")
        self.assertContains(quick, 'data-billing-mode="quick"')
        self.assertContains(quick, "POS visuel")
        self.assertContains(quick, "Billing rapide")
        self.assertNotContains(quick, 'data-phone="0991234567"')
        clients = self.client.get(reverse("facturation:search"), {"entity":"client", "context":"pos", "q":"0991234567"}).json()["results"]
        self.assertEqual(clients[0]["phone"], "0991234567")
        self.assertEqual(quick.context["default_billing_mode"], "quick")
        self.assertContains(quick, 'id="posDefaultBillingMode"')
        visual = self.client.get(reverse("facturation:pos-view"), {"billing":"visual"})
        self.assertEqual(visual.status_code, 200)
        self.assertTrue(visual.context["compact_sidebar"])
        self.assertContains(visual, 'class="theme-light pos-compact-sidebar"')
        self.assertIn("PEMPASE", visual.context["produits_json"])
        self.assertFalse(visual.context["billing_quick"])

    def test_pos_launch_turns_sidebar_into_icon_rail_only_on_point_of_sale(self):
        """La rampe d'icones s'active des l'ouverture du POS, sans toucher aux autres pages."""
        for params in ({}, {"billing": "visual"}):
            with self.subTest(params=params):
                response = self.client.get(reverse("facturation:pos-view"), params)
                self.assertContains(response, 'class="sidebar-rail-toggle"')
                self.assertContains(response, 'class="sidebar-rail-backdrop"')
                self.assertContains(response, "assets/js/faccontrol-sidebar-rail.js")

        UserMenuPermission.objects.update_or_create(
            user=self.user, permission_key="clients", defaults={"is_allowed": True},
        )
        other_page = self.client.get(reverse("facturation:client-list"))
        self.assertEqual(other_page.status_code, 200)
        self.assertNotContains(other_page, "pos-compact-sidebar")
        self.assertNotContains(other_page, "sidebar-rail-toggle")
        self.assertNotContains(other_page, "faccontrol-sidebar-rail.js")

    def test_default_mode_is_saved_and_survives_reconnection(self):
        for mode in ("visual", "quick"):
            with self.subTest(mode=mode):
                saved = self.client.post(reverse("facturation:pos-default-billing"), {"billing_mode": mode})
                self.assertEqual(saved.status_code, 200)
                self.assertEqual(saved.json(), {"success": True, "billing_mode": mode})
                cookie = saved.cookies["faccontrol_default_billing"]
                self.assertEqual(cookie["max-age"], 31536000)
                self.assertTrue(cookie["httponly"])
                self.client.post(reverse("facturation:logout"))
                self.client.force_login(self.user)
                page = self.client.get(reverse("facturation:pos-view"))
                self.assertEqual(page.context["default_billing_mode"], mode)
                self.assertEqual(page.context["billing_quick"], mode == "quick")

    def test_explicit_mode_overrides_default_without_changing_preference(self):
        for default, explicit in (("visual", "quick"), ("quick", "visual")):
            with self.subTest(default=default):
                self.client.cookies["faccontrol_default_billing"] = default
                page = self.client.get(reverse("facturation:pos-view"), {"billing": explicit})
                self.assertEqual(page.context["default_billing_mode"], default)
                self.assertEqual(page.context["billing_quick"], explicit == "quick")
                page = self.client.get(reverse("facturation:pos-view"), {"billing": "invalid"})
                self.assertEqual(page.context["billing_quick"], default == "quick")

    def test_invalid_default_is_ignored_and_cannot_be_saved(self):
        self.client.cookies["faccontrol_default_billing"] = "invalid"
        page = self.client.get(reverse("facturation:pos-view"))
        self.assertTrue(page.context["billing_quick"])
        url = reverse("facturation:pos-default-billing")
        for payload in ({}, {"billing_mode": "invalid"}):
            response = self.client.post(url, payload)
            self.assertEqual(response.status_code, 400)
            self.assertNotIn("faccontrol_default_billing", response.cookies)
        self.assertEqual(self.client.get(url).status_code, 405)

    def test_saving_default_requires_pos_permission_and_csrf(self):
        url = reverse("facturation:pos-default-billing")
        csrf_client = TestClient(enforce_csrf_checks=True)
        csrf_client.force_login(self.user)
        self.assertEqual(csrf_client.post(url, {"billing_mode": "visual"}).status_code, 403)
        UserMenuPermission.objects.create(user=self.user, permission_key="pos", is_allowed=False)
        denied = self.client.post(url, {"billing_mode": "visual"})
        self.assertNotEqual(denied.status_code, 200)
        self.assertNotIn("faccontrol_default_billing", denied.cookies)

    def test_switching_pdv_preserves_current_mode_over_default(self):
        for default, current in (("quick", "visual"), ("visual", "quick")):
            with self.subTest(current=current):
                self.client.cookies["faccontrol_default_billing"] = default
                response = self.client.post(reverse("facturation:pos-switch"), {
                    "point_de_vente_id": self.pdv.pk, "billing_mode": current,
                }, follow=True)
                self.assertEqual(response.context["billing_quick"], current == "quick")
                self.assertEqual(response.context["active_pos_id"], self.pdv.pk)

    def test_exact_code_prefix_code_exact_name_prefix_name_then_substring(self):
        prefix_code = self.product_with_stock("Code prefix", "GEDETEST01-2")
        exact_name = self.product_with_stock("GEDETEST01", "NAME-1")
        prefix_name = self.product_with_stock("GEDETEST01 GRAND", "NAME-2")
        contains = self.product_with_stock("Article GEDETEST01 enfant", "NAME-3")
        response = self.client.get(self.url, {"q":"gedetest01"})
        self.assertEqual([row["id"] for row in response.json()["results"]],
            [self.product.pk, prefix_code.pk, exact_name.pk, prefix_name.pk, contains.pk])

    def test_partial_name_case_and_accent_search_and_default_price(self):
        accented = self.product_with_stock("Crème PEMPASE Enfant", "CREME-01")
        for query in ("pem", "PEM", "empas", "creme", "crème"):
            with self.subTest(query=query):
                rows = self.client.get(self.url, {"q":query}).json()["results"]
                self.assertIn(accented.pk, [row["id"] for row in rows])
        row = self.client.get(self.url, {"q":"GEDETEST01"}).json()["results"][0]
        prices = {pack["id"]: pack["prix"] for pack in row["conditionnements"]}
        self.assertEqual(prices, {self.piece.pk:1000, self.packet.pk:5500, self.carton.pk:9000})
        self.assertEqual(row["stock"], 100)
        self.assertEqual(row["conditionnement_defaut_id"], self.piece.pk)

    def test_suggestions_are_limited_global_and_do_not_include_images(self):
        for index in range(20):
            self.product_with_stock("PEMPASE " + str(index), "MATCH-" + str(index))
        foreign = self.product_with_stock("PEMPASE AUTRE", "FOREIGN", self.other_pdv)
        inactive = self.product_with_stock("PEMPASE INACTIF", "INACTIVE")
        Produit.objects.filter(pk=inactive.pk).update(actif=False)
        Produit.objects.filter(pk=self.product.pk).update(image="produits/unused.png")
        results = self.client.get(self.url, {"q":"pem"}).json()["results"]
        self.assertEqual(len(results), 15)
        self.assertNotIn(inactive.pk, [row["id"] for row in results])
        foreign_row = self.client.get(self.url, {"q":"FOREIGN"}).json()["results"][0]
        self.assertEqual((foreign_row["id"], foreign_row["stock"]), (foreign.pk, 0))
        row = self.client.get(self.url, {"ids":str(self.product.pk)}).json()["results"][0]
        self.assertEqual(row["image_url"], "")
        self.assertEqual(self.client.get(self.url).json()["results"], [])

    def test_catalogue_payload_is_identical_to_visual_pos_without_n_plus_one(self):
        for index in range(17):
            self.product_with_stock("PEMPASE extra " + str(index), "EXTRA-" + str(index))
        qs = search_pos_products(pos_product_queryset(self.pdv), "pem")[:15]
        with self.assertNumQueries(4):
            rows = build_pos_catalogue(qs, self.config, self.pdv, include_images=False)
        visual = self.client.get(reverse("facturation:pos-view"), {"billing":"visual"})
        import json
        indexed = {row["id"]: row for row in json.loads(visual.context["produits_json"])}
        for row in rows:
            self.assertEqual(row, indexed[row["id"]])

    def test_permissions_and_pdv_price_only_products_are_preserved(self):
        price_only = Produit.objects.create(nom="Prix PDV seulement", code_sku="PRICE-ONLY", prix_vente=1000)
        ProduitPointVentePrix.objects.create(produit=price_only, conditionnement=price_only.conditionnements.get(),
            point_de_vente=self.pdv, prix_vente=1200)
        row = self.client.get(self.url, {"q":"PRICE-ONLY"}).json()["results"][0]
        self.assertEqual((row["stock"], row["prix"]), (0, 1200))
        UserMenuPermission.objects.create(user=self.user, permission_key="pos", is_allowed=False)
        response = self.client.get(self.url, {"q":"pem"})
        self.assertNotEqual(response.status_code, 200)

    def test_restore_ids_and_visual_pages_are_bounded_and_global(self):
        foreign = self.product_with_stock("Autre article", "OTHER", self.other_pdv)
        rows = self.client.get(self.url, {"ids":f"{self.product.pk},{foreign.pk}"}).json()["results"]
        self.assertEqual([row["id"] for row in rows], [foreign.pk, self.product.pk])
        self.assertEqual(next(row for row in rows if row["id"] == foreign.pk)["stock"], 0)
        self.assertEqual(self.client.get(self.url, {"ids":"bad"}).status_code, 400)
        self.assertEqual(self.client.get(self.url, {"offset":"-1", "visual":"1"}).status_code, 400)
        self.assertEqual(self.client.get(self.url, {"visual":"1"}).json()["next_offset"], None)

    def test_product_stocked_only_elsewhere_is_sold_with_minus_one_in_current_pdv(self):
        foreign = self.product_with_stock("Article autre magasin", "OTHER-SALE", self.other_pdv)
        with patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            return_value={
                "success": True,
                "channel": "MCF",
                "commande_id": 1,
                "fiscal_transaction_id": "global-pos-product",
            },
        ):
            response = self.client.post(
                reverse("facturation:pos-view"),
                {
                    "client_id": self.customer.pk,
                    "panier": [{"id": foreign.pk, "qty": 1}],
                },
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200, response.content)
        current_stock = StockPointDeVente.objects.get(
            produit=foreign,
            point_de_vente=self.pdv,
        )
        other_stock = StockPointDeVente.objects.get(
            produit=foreign,
            point_de_vente=self.other_pdv,
        )
        self.assertEqual(current_stock.quantite, Decimal("-1.000"))
        self.assertEqual(other_stock.quantite, Decimal("100.000"))
        mouvement = MouvementStock.objects.get(
            commande_associee_id=response.json()["commande_id"]
        )
        self.assertEqual((mouvement.stock_id, mouvement.quantite), (current_stock.pk, Decimal("-1.000")))

    def test_invoice_opened_from_pos_renders_in_one_pass_with_constant_queries(self):
        """Facture validee : meme rampe que le POS, styles dans l'en-tete, pas de N+1."""

        def sale(lines):
            with patch("facturation.views.FiscalOrchestrator.fiscalize_commande", return_value={"success":True, "channel":"MCF", "commande_id":1, "fiscal_transaction_id":f"one-pass-{len(lines)}"}):
                response = self.client.post(reverse("facturation:pos-view") + "?billing=quick", {
                    "client_id":self.customer.pk, "panier":lines,
                    "paiements":[{"montant_verse":100000, "devise":"CDF", "mode":"ESPECES", "taux":1}],
                }, content_type="application/json")
            self.assertEqual(response.status_code, 200, response.content)
            return reverse("facturation:facture-detail", args=[response.json()["commande_id"]]) + "?billing=quick"

        one_line = sale([{"id":self.product.pk, "conditionnement_id":self.piece.pk, "qty":1}])
        two_lines = sale([
            {"id":self.product.pk, "conditionnement_id":self.piece.pk, "qty":1},
            {"id":self.product.pk, "conditionnement_id":self.carton.pk, "qty":1},
        ])
        self.client.get(one_line)
        with CaptureQueriesContext(connection) as small:
            response = self.client.get(one_line)
        with CaptureQueriesContext(connection) as large:
            self.client.get(two_lines)
        self.assertEqual(len(large.captured_queries), len(small.captured_queries))

        html = response.content.decode()
        self.assertIn("pos-compact-sidebar", html[html.index("<body"):html.index(">", html.index("<body"))])
        head_end = html.index("</head>")
        for stylesheet in ("document_preview.css", "invoice_print_output.css"):
            self.assertLess(html.index(stylesheet), head_end)
        # Ouverte depuis la liste des factures, la page garde la navigation complete.
        plain = self.client.get(one_line.split("?")[0]).content.decode()
        self.assertNotIn("pos-compact-sidebar", plain[plain.index("<body"):plain.index(">", plain.index("<body"))])

    def test_quick_sale_uses_normal_fiscal_stock_snapshots_and_multiple_payments(self):
        with patch("facturation.views.FiscalOrchestrator.fiscalize_commande", return_value={"success":True, "channel":"MCF", "commande_id":1, "fiscal_transaction_id":"quick-test"}) as fiscalize:
            response = self.client.post(reverse("facturation:pos-view") + "?billing=quick", {
                "client_id":self.customer.pk, "panier":[
                    {"id":self.product.pk, "conditionnement_id":self.carton.pk, "qty":2},
                    {"id":self.product.pk, "conditionnement_id":self.piece.pk, "qty":3},
                ], "paiements":[
                    {"montant_verse":10000, "devise":"CDF", "mode":"ESPECES", "taux":1},
                    {"montant_verse":14360, "devise":"CDF", "mode":"CARD", "taux":1},
                ],
            }, content_type="application/json")
        self.assertEqual(response.status_code, 200, response.content)
        self.assertTrue(response.json()["success"])
        self.assertEqual(
            response.json()["redirect_url"],
            reverse(
                "facturation:facture-detail",
                args=[response.json()["commande_id"]],
            ),
        )
        fiscalize.assert_called_once()
        sale = Commande.objects.get()
        self.assertEqual((sale.montant_total_ht, sale.tva_montant, sale.montant_total),
            (Decimal("21000"), Decimal("3360"), Decimal("24360")))
        self.assertEqual(LigneCommande.objects.count(), 2)
        self.assertEqual(sum(LigneCommande.objects.values_list("quantite_physique", flat=True)), 27)
        self.assertEqual(StockPointDeVente.objects.get(produit=self.product).quantite, 73)
        self.assertEqual(MouvementStock.objects.count(), 2)
        self.assertEqual(Paiement.objects.count(), 2)


class QuickBillingVolumeTests(TestCase):
    def test_search_and_initial_quick_load_with_3000_products(self):
        import time

        cache.clear()
        pdv = PointDeVente.objects.create(nom="Grand catalogue")
        user = get_user_model().objects.create_user(username="volume", email="volume@example.com", point_de_vente=pdv)
        config = Configuration.objects.create(taux_change=1)
        products = [Produit.objects.create(nom=f"Article volume {index:04d}", code_sku=f"VOLUME-{index:04d}", prix_vente=10) for index in range(3000)]
        StockPointDeVente.objects.bulk_create([StockPointDeVente(produit=product, point_de_vente=pdv, quantite=100) for product in products])
        self.client.force_login(user)
        self.client.get(reverse("facturation:pos-view"), {"billing":"quick"})  # Chauffer referentiels et permissions.
        start = time.perf_counter()
        with CaptureQueriesContext(connection) as queries:
            response = self.client.get(reverse("facturation:pos-catalogue"), {"q":"volume"})
        elapsed = time.perf_counter() - start
        self.assertEqual(len(response.json()["results"]), 15)
        self.assertLessEqual(len(queries), 12)
        with self.assertNumQueries(4):
            build_pos_catalogue(search_pos_products(pos_product_queryset(pdv), "VOLUME-2999")[:15], config, pdv)
        with CaptureQueriesContext(connection) as page_queries:
            page = self.client.get(reverse("facturation:pos-view"), {"billing":"quick"})
        self.assertEqual(page.context["produits_json"], "[]")
        self.assertFalse(any('FROM "facturation_produit"' in row["sql"] for row in page_queries))
        print(f"Quick Billing 3000 produits : recherche {len(queries)} requetes / {elapsed * 1000:.1f} ms ; ouverture {len(page_queries)} requetes, 0 produit hydrate.")
        cache.clear()
