"""Tests du POS et du stock en conditionnements commerciaux."""

import json
from decimal import Decimal
from unittest.mock import patch

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.test import TestCase
from django.urls import reverse

from dgi.models import ItemType, TaxGroup

from .fiscal_cancellation import FiscalCancellationService
from .fiscal_preparation import FiscalPayloadBuilder
from .models import (
    Commande,
    Client,
    ConditionnementProduit,
    Configuration,
    LigneCommande,
    MouvementStock,
    Paiement,
    PointDeVente,
    Produit,
    ProduitPointVentePrix,
    StockPointDeVente,
)


class VenteConditionnementPOSTests(TestCase):
    def setUp(self):
        self.pdv = PointDeVente.objects.create(nom="Boutique conditionnements")
        self.user = get_user_model().objects.create_user(
            username="vendeur-conditionnements",
            email="vendeur-conditionnements@test.com",
            password="secret",
            point_de_vente=self.pdv,
        )
        self.item_type = ItemType.objects.create(code="BIE-PACK", name="Bien")
        self.tax_group = TaxGroup.objects.create(
            code="BP",
            name="Taxable conditionnements",
            tax=Decimal("16"),
        )
        self.produit = Produit.objects.create(
            nom="Jus Orange 33 cl",
            code_sku="JUS-PACK",
            unite_mesure="Bouteille",
            prix_vente=Decimal("1000"),
            taxgroup=self.tax_group,
            typeart=self.item_type,
            actif=True,
        )
        self.bouteille = self.produit.conditionnements.get()
        self.paquet = ConditionnementProduit.objects.create(
            produit=self.produit,
            code="JUS-PACK-6",
            libelle="Paquet de 6",
            facteur_conversion=Decimal("6"),
            prix_vente=Decimal("5500"),
            vendable=True,
            achetable=True,
            fractionnable=False,
            actif=True,
        )
        self.carton = ConditionnementProduit.objects.create(
            produit=self.produit,
            code="JUS-CARTON-24",
            libelle="Carton de 24",
            facteur_conversion=Decimal("24"),
            prix_vente=Decimal("20000"),
            vendable=True,
            achetable=True,
            fractionnable=False,
            actif=True,
        )
        self.stock = StockPointDeVente.objects.create(
            point_de_vente=self.pdv,
            produit=self.produit,
            quantite=Decimal("200"),
        )
        Configuration.objects.create(
            taux_change=Decimal("1"),
            nif="A1234567Q",
            isf_dgi="CD01000000-1",
            mode_dgi="ttc",
            type_dgi="FV",
        )
        self.customer = Client.objects.create(nom_complet="Client conditionnements")
        self.client.force_login(self.user)

    def _post_sale(self, panier):
        with patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            return_value={
                "success": True,
                "channel": "MCF",
                "commande_id": 1,
                "fiscal_transaction_id": "pack-test",
            },
        ):
            return self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps({"panier": panier, "client_id": self.customer.pk}),
                content_type="application/json",
            )

    def test_new_pos_sale_freezes_cump_and_total_cost_under_stock_lock(self):
        self.stock.cump = Decimal("635.294118")
        self.stock.save()
        response = self._post_sale([{"id": self.produit.pk, "conditionnement_id": self.paquet.pk, "qty": 2}])
        self.assertEqual(response.status_code, 200, response.content)
        line = LigneCommande.objects.get()
        self.assertEqual(line.cout_unitaire_base_snapshot, Decimal("635.294118"))
        self.assertEqual(line.cout_total_snapshot, Decimal("7623.529416"))
        self.assertEqual(line.quantite_physique_cout_snapshot, Decimal("12"))
        self.assertEqual(line.mouvements_stock.get().cump_avant, line.cout_unitaire_base_snapshot)

    def _assert_stock_sale_allowed(self, panier):
        with patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            return_value={
                "success": True,
                "channel": "MCF",
                "commande_id": 1,
                "fiscal_transaction_id": "negative-stock-pack-test",
            },
        ) as fiscalize:
            response = self.client.post(reverse("facturation:pos-view"),
                data=json.dumps({"panier": panier, "client_id": self.customer.pk,
                    "paiement": {"montant_verse": 50000, "devise": "CDF", "taux": 1, "mode": "ESPECES"}}),
                content_type="application/json")
        self.assertEqual(response.status_code, 200, response.content)
        fiscalize.assert_called_once()
        return response

    def test_depleted_absent_and_negative_stock_allow_sales_with_negative_history(self):
        panier = [{"id": self.produit.pk, "conditionnement_id": self.bouteille.pk, "qty": 1}]
        for quantity in (Decimal("0"), Decimal("-2"), None):
            with self.subTest(stock=quantity):
                if quantity is None:
                    StockPointDeVente.objects.filter(
                        point_de_vente=self.pdv,
                        produit=self.produit,
                    ).delete()
                else:
                    StockPointDeVente.objects.update_or_create(
                        point_de_vente=self.pdv,
                        produit=self.produit,
                        defaults={"quantite": quantity},
                    )
                response = self._assert_stock_sale_allowed(panier)
                stock = StockPointDeVente.objects.get(
                    point_de_vente=self.pdv,
                    produit=self.produit,
                )
                expected_before = quantity if quantity is not None else Decimal("0")
                mouvement = MouvementStock.objects.get(
                    commande_associee_id=response.json()["commande_id"]
                )
                self.assertEqual(mouvement.stock_avant, expected_before)
                self.assertEqual(mouvement.stock_apres, expected_before - Decimal("1"))
                self.assertEqual(stock.quantite, expected_before - Decimal("1"))

    def test_superadministrator_can_sell_an_exhausted_article(self):
        self.user.role = "ADMIN"
        self.user.is_superuser = True
        self.user.save(update_fields=["role", "is_superuser"])
        StockPointDeVente.objects.filter(pk=self.stock.pk).update(quantite=0)
        self._assert_stock_sale_allowed(
            [{"id": self.produit.pk, "conditionnement_id": self.carton.pk, "qty": 1}]
        )
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("-24.000"))

    def test_last_carton_is_sold_then_the_next_sale_makes_stock_negative(self):
        StockPointDeVente.objects.filter(pk=self.stock.pk).update(quantite=24)
        panier = [{"id": self.produit.pk, "conditionnement_id": self.carton.pk, "qty": 1}]
        response = self._post_sale(panier)
        self.assertEqual(response.status_code, 200, response.content)
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("0"))
        response = self._post_sale(panier)
        self.assertEqual(response.status_code, 200, response.content)
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("-24.000"))

    def test_mixed_packaging_shortage_records_all_movements(self):
        StockPointDeVente.objects.filter(pk=self.stock.pk).update(quantite=16)
        response = self._post_sale([
            {"id": self.produit.pk, "conditionnement_id": self.paquet.pk, "qty": 2},
            {"id": self.produit.pk, "conditionnement_id": self.bouteille.pk, "qty": 5},
        ])
        self.assertEqual(response.status_code, 200, response.content)
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("-1.000"))
        self.assertEqual(
            list(MouvementStock.objects.order_by("pk").values_list("quantite", flat=True)),
            [Decimal("-12.000"), Decimal("-5.000")],
        )

    def test_one_exhausted_product_does_not_reject_the_entire_cart(self):
        available_product = Produit.objects.create(nom="Article disponible", code_sku="DISPO-POS",
            prix_vente=1000, taxgroup=self.tax_group, typeart=self.item_type, actif=True)
        available_stock = StockPointDeVente.objects.create(
            point_de_vente=self.pdv, produit=available_product, quantite=10
        )
        StockPointDeVente.objects.filter(pk=self.stock.pk).update(quantite=0)
        response = self._post_sale([
            {"id": available_product.pk, "qty": 1},
            {"id": self.produit.pk, "conditionnement_id": self.bouteille.pk, "qty": 1},
        ])
        self.assertEqual(response.status_code, 200, response.content)
        available_stock.refresh_from_db()
        self.stock.refresh_from_db()
        self.assertEqual(available_stock.quantite, Decimal("9.000"))
        self.assertEqual(self.stock.quantite, Decimal("-1.000"))

    def test_english_pos_allows_zero_stock_without_stock_error(self):
        self.client.cookies[settings.LANGUAGE_COOKIE_NAME] = "en"
        StockPointDeVente.objects.filter(pk=self.stock.pk).update(quantite=0)
        response = self._post_sale(
            [{"id": self.produit.pk, "conditionnement_id": self.bouteille.pk, "qty": 1}]
        )
        self.assertEqual(response.status_code, 200, response.content)
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("-1.000"))

    def test_pos_html_does_not_contain_stock_blocking_guards(self):
        response = self.client.get(reverse("facturation:pos-view"))
        self.assertEqual(response.status_code, 200)
        self.assertNotContains(response, "if (!validateCartStock()) return;")
        self.assertNotContains(response, 'max="${getMaximumLineQuantity(item)}"')
        self.assertNotContains(response, "stockExhaustedMessage")

    def test_catalogue_exposes_active_vendable_conditionnements_and_pdv_price(self):
        ProduitPointVentePrix.objects.create(
            produit=self.produit,
            conditionnement=self.paquet,
            point_de_vente=self.pdv,
            prix_vente=Decimal("5200"),
            actif=True,
        )
        response = self.client.get(reverse("facturation:pos-view"), {"billing": "visual"})
        payload = json.loads(response.context["produits_json"])[0]
        conditionnements = {item["id"]: item for item in payload["conditionnements"]}

        self.assertEqual(conditionnements[self.bouteille.id]["prix"], 1000.0)
        self.assertEqual(conditionnements[self.paquet.id]["prix"], 5200.0)
        self.assertEqual(conditionnements[self.carton.id]["prix"], 20000.0)
        self.assertEqual(payload["conditionnement_defaut_id"], self.bouteille.id)

    def test_same_product_with_two_conditionnements_consumes_aggregated_physical_stock(self):
        response = self._post_sale(
            [
                {"id": self.produit.id, "conditionnement_id": self.paquet.id, "qty": "2", "remise": 0},
                {"id": self.produit.id, "conditionnement_id": self.bouteille.id, "qty": "3", "remise": 0},
            ]
        )
        self.assertEqual(response.status_code, 200, response.content)
        commande = Commande.objects.get(pk=response.json()["commande_id"])
        lignes = {ligne.conditionnement_id: ligne for ligne in commande.lignes.all()}
        self.assertEqual(lignes[self.paquet.id].quantite, Decimal("2.000"))
        self.assertEqual(lignes[self.paquet.id].quantite_physique, Decimal("12.000"))
        self.assertEqual(lignes[self.paquet.id].prix_unitaire, Decimal("5500.00"))
        self.assertEqual(lignes[self.bouteille.id].quantite_physique, Decimal("3.000"))
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("185.000"))
        self.assertEqual(
            sum(
                (m.quantite for m in MouvementStock.objects.filter(commande_associee=commande)),
                Decimal("0"),
            ),
            Decimal("-15.000"),
        )

    def test_carton_factor_24_uses_commercial_quantity_and_physical_movement(self):
        response = self._post_sale(
            [{"id": self.produit.id, "conditionnement_id": self.carton.id, "qty": "2", "remise": 0}]
        )
        self.assertEqual(response.status_code, 200, response.content)
        ligne = Commande.objects.get(pk=response.json()["commande_id"]).lignes.get()
        self.assertEqual(ligne.quantite, Decimal("2.000"))
        self.assertEqual(ligne.facteur_conversion_snapshot, Decimal("24.000"))
        self.assertEqual(ligne.quantite_physique, Decimal("48.000"))
        self.assertEqual(ligne.mouvements_stock.get().quantite, Decimal("-48.000"))

    def test_stock_projection_aggregates_all_packagings_after_sale(self):
        self.stock.quantite = Decimal("16")
        self.stock.save(update_fields=["quantite", "updated_at"])
        response = self._post_sale(
            [
                {"id": self.produit.id, "conditionnement_id": self.paquet.id, "qty": "2", "remise": 0},
                {"id": self.produit.id, "conditionnement_id": self.bouteille.id, "qty": "5", "remise": 0},
            ]
        )
        self.assertEqual(response.status_code, 200, response.content)
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("-1.000"))
        self.assertEqual(
            sum(MouvementStock.objects.values_list("quantite", flat=True), Decimal("0")),
            Decimal("-17.000"),
        )

    def test_rejects_inactive_non_vendable_and_fractional_non_fractionable(self):
        self.paquet.vendable = False
        self.paquet.save()
        response = self._post_sale(
            [{"id": self.produit.id, "conditionnement_id": self.paquet.id, "qty": "1", "remise": 0}]
        )
        self.assertEqual(response.status_code, 400)
        self.paquet.vendable = True
        self.paquet.actif = False
        self.paquet.save()
        response = self._post_sale(
            [{"id": self.produit.id, "conditionnement_id": self.paquet.id, "qty": "1", "remise": 0}]
        )
        self.assertEqual(response.status_code, 400)
        response = self._post_sale(
            [{"id": self.produit.id, "conditionnement_id": self.carton.id, "qty": "1.5", "remise": 0}]
        )
        self.assertEqual(response.status_code, 400)
        self.assertIn("fractionnaire", response.json()["error"])

    def test_fractional_quantity_is_allowed_when_packaging_is_fractionable(self):
        self.paquet.fractionnable = True
        self.paquet.save()
        response = self._post_sale(
            [{"id": self.produit.id, "conditionnement_id": self.paquet.id, "qty": "1.5", "remise": 0}]
        )
        self.assertEqual(response.status_code, 200, response.content)
        ligne = Commande.objects.get(pk=response.json()["commande_id"]).lignes.get()
        self.assertEqual(ligne.quantite, Decimal("1.500"))
        self.assertEqual(ligne.quantite_physique, Decimal("9.000"))

    def test_invoice_and_dgi_keep_commercial_quantity_and_product_tax_group(self):
        response = self._post_sale(
            [{"id": self.produit.id, "conditionnement_id": self.paquet.id, "qty": "2", "remise": 0}]
        )
        commande = Commande.objects.get(pk=response.json()["commande_id"])
        item = FiscalPayloadBuilder().build(commande)["items"][0]
        self.assertEqual(item["quantity"], Decimal("2.000"))
        self.assertEqual(item["unit_price"], Decimal("5500.00"))
        self.assertEqual(item["tax_group"], self.tax_group.code)

        facture = self.client.get(reverse("facturation:facture-detail", args=[commande.pk]))
        self.assertContains(facture, "Jus Orange 33 cl — Paquet de 6")
        self.assertContains(facture, ">2,000<", html=False)

    def test_cancellation_restores_snapshot_physical_quantity(self):
        response = self._post_sale(
            [{"id": self.produit.id, "conditionnement_id": self.paquet.id, "qty": "2", "remise": 0}]
        )
        source = Commande.objects.get(pk=response.json()["commande_id"])
        service = FiscalCancellationService()
        cancel_lines = service._build_cancel_lines(source)
        ConditionnementProduit.objects.filter(pk=self.paquet.pk).update(facteur_conversion=Decimal("10"))
        avoir = Commande.objects.create(
            point_de_vente=self.pdv,
            vendeur=self.user,
            client=self.customer,
            type_facture="FA",
            facture_origine=source,
        )
        service._restore_stock_for_credit_note(source, avoir, cancel_lines, self.user)
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("200.000"))
        self.assertEqual(cancel_lines[0]["quantite_physique"], Decimal("12.000"))

    def test_credit_note_line_keeps_explicit_sale_snapshots(self):
        response = self._post_sale(
            [{"id": self.produit.id, "conditionnement_id": self.paquet.id, "qty": "2", "remise": 0}]
        )
        source_line = Commande.objects.get(pk=response.json()["commande_id"]).lignes.get()
        ConditionnementProduit.objects.filter(pk=self.paquet.pk).update(
            libelle="Paquet courant",
            facteur_conversion=Decimal("10"),
        )
        avoir = Commande.objects.create(
            point_de_vente=self.pdv,
            vendeur=self.user,
            client=self.customer,
            type_facture="FA",
            facture_origine=source_line.commande,
        )

        copied = LigneCommande.objects.create(
            commande=avoir,
            produit=self.produit,
            conditionnement=self.paquet,
            conditionnement_libelle_snapshot=source_line.conditionnement_libelle_snapshot,
            facteur_conversion_snapshot=source_line.facteur_conversion_snapshot,
            quantite=source_line.quantite,
            prix_unitaire=source_line.prix_unitaire,
            remise=source_line.remise,
            sous_total=source_line.sous_total,
            type_article_dgi_snapshot=source_line.type_article_dgi_snapshot,
            groupe_taxation_snapshot=source_line.groupe_taxation_snapshot,
        )

        self.assertEqual(copied.conditionnement_libelle_snapshot, "Paquet de 6")
        self.assertEqual(copied.facteur_conversion_snapshot, Decimal("6.000"))
        self.assertEqual(copied.quantite_physique, Decimal("12.000"))

    def test_used_packaging_factor_is_protected_but_price_can_change(self):
        response = self._post_sale(
            [{"id": self.produit.id, "conditionnement_id": self.paquet.id, "qty": "1", "remise": 0}]
        )
        self.assertEqual(response.status_code, 200)
        self.paquet.facteur_conversion = Decimal("5")
        with self.assertRaises(ValidationError):
            self.paquet.save()
        self.paquet.refresh_from_db()
        self.paquet.prix_vente = Decimal("5300")
        self.paquet.save()
        self.assertEqual(self.paquet.prix_vente, Decimal("5300"))

    def test_legacy_line_remains_factor_one_without_packaging_label(self):
        commande = Commande.objects.create(
            point_de_vente=self.pdv,
            vendeur=self.user,
            client=self.customer,
            type_facture="FV",
            montant_total=Decimal("2000"),
        )
        ligne = LigneCommande.objects.create(
            commande=commande,
            produit=self.produit,
            quantite=Decimal("2"),
            prix_unitaire=Decimal("1000"),
            remise=Decimal("0"),
            sous_total=Decimal("2000"),
        )
        self.assertIsNone(ligne.conditionnement)
        self.assertEqual(ligne.facteur_conversion_snapshot, Decimal("1"))
        self.assertEqual(ligne.quantite_physique, Decimal("2.000"))
        facture = self.client.get(reverse("facturation:facture-detail", args=[commande.pk]))
        self.assertContains(facture, "Jus Orange 33 cl")
        self.assertNotContains(facture, "Jus Orange 33 cl — Bouteille")
