"""Régressions POS : stock non bloquant et fiscalité produit obligatoire."""

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.test import TestCase
from django.urls import reverse

from dgi.models import ItemType, TaxGroup

from .models import (
    Commande,
    ConditionnementProduit,
    Configuration,
    PendingSale,
    PointDeVente,
    Produit,
    StockPointDeVente,
)


class POSProductFiscalValidationTests(TestCase):
    """Le stock informe le POS tandis que le groupe fiscal reste bloquant."""

    def setUp(self):
        self.pdv = PointDeVente.objects.create(nom="PDV validation fiscale")
        self.user = get_user_model().objects.create_user(
            username="pos-fiscal-validation",
            email="pos-fiscal-validation@example.com",
            role="VENDEUR",
            point_de_vente=self.pdv,
        )
        Configuration.objects.create(
            taux_change=Decimal("1"),
            mode_dgi="ttc",
            type_dgi="FV",
            nif="A1234567Q",
            isf_dgi="CD01000000-1",
            fiscal_primary_channel="MCF",
            fiscal_fallback_mode="DISABLED",
            require_security_before_save=False,
        )
        self.tax_group, _ = TaxGroup.objects.update_or_create(
            code="B",
            defaults={"name": "Groupe B", "tax": Decimal("16"), "is_active": True},
        )
        self.item_type, _ = ItemType.objects.update_or_create(
            code="BIE",
            defaults={"name": "Biens", "is_active": True},
        )
        self.product = Produit.objects.create(
            nom="Article fiscal POS",
            code_sku="POS-FISCAL-001",
            prix_vente=Decimal("100"),
            taxgroup=self.tax_group,
            typeart=self.item_type,
            actif=True,
        )
        self.stock = StockPointDeVente.objects.create(
            point_de_vente=self.pdv,
            produit=self.product,
            quantite=Decimal("10"),
        )
        self.client.force_login(self.user)

    def _set_stock(self, quantity):
        StockPointDeVente.objects.update_or_create(
            point_de_vente=self.pdv,
            produit=self.product,
            defaults={"quantite": Decimal(str(quantity))},
        )

    def _post_sale(self, quantity, *, conditionnement=None, pending_sale_id=None):
        line = {"id": self.product.pk, "qty": quantity, "remise": 0}
        if conditionnement is not None:
            line["conditionnement_id"] = conditionnement.pk
        payload = {
            "panier": [line],
            "document_mode": "FV",
            "remise_globale": 0,
            "paiements": [],
        }
        if pending_sale_id is not None:
            payload["pending_sale_id"] = pending_sale_id

        with patch(
            "facturation.fiscal_orchestrator.FiscalOrchestrator._call_channel",
            return_value={"channel": "MCF", "security": {}},
        ) as fiscal_channel:
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps(payload),
                content_type="application/json",
            )
        return response, fiscal_channel

    def _assert_sale_stock(self, *, before, sold, after):
        self._set_stock(before)
        response, fiscal_channel = self._post_sale(sold)
        self.assertEqual(response.status_code, 200, response.content)
        fiscal_channel.assert_called_once()
        stock = StockPointDeVente.objects.get(point_de_vente=self.pdv, produit=self.product)
        self.assertEqual(stock.quantite, Decimal(str(after)))

    def test_positive_stock_sale_is_allowed(self):
        self._assert_sale_stock(before=10, sold=2, after=8)

    def test_zero_stock_sale_is_allowed_and_becomes_negative(self):
        self._assert_sale_stock(before=0, sold=2, after=-2)

    def test_sale_above_available_stock_is_allowed(self):
        self._assert_sale_stock(before=1, sold=5, after=-4)

    def test_already_negative_stock_sale_is_allowed(self):
        self._assert_sale_stock(before=-3, sold=2, after=-5)

    def test_product_without_tax_group_is_rejected_with_bilingual_message(self):
        self.product.taxgroup = None
        self.product.save(update_fields=["taxgroup"])

        response, fiscal_channel = self._post_sale(1)
        self.assertEqual(response.status_code, 400, response.content)
        self.assertEqual(
            response.json()["error"],
            "Le produit « Article fiscal POS » ne possède pas de groupe de taxation valide. "
            "Veuillez configurer son groupe de taxation avant de le facturer.",
        )
        fiscal_channel.assert_not_called()
        self.assertEqual(Commande.objects.count(), 0)
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("10.000"))

        self.client.cookies[settings.LANGUAGE_COOKIE_NAME] = "en"
        response, fiscal_channel = self._post_sale(1)
        self.assertEqual(response.status_code, 400, response.content)
        self.assertEqual(
            response.json()["error"],
            "The product “Article fiscal POS” does not have a valid tax group. "
            "Please configure its tax group before invoicing.",
        )
        fiscal_channel.assert_not_called()
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("10.000"))

    def test_legacy_product_without_item_type_uses_existing_goods_mapping(self):
        self.product.typeart = None
        self.product.save(update_fields=["typeart"])

        response, fiscal_channel = self._post_sale(1)
        self.assertEqual(response.status_code, 200, response.content)
        line = Commande.objects.get(pk=response.json()["commande_id"]).lignes.get()
        self.assertEqual(line.type_article_dgi_snapshot, "BIE")
        prepared_payload = fiscal_channel.call_args.args[2]
        self.assertEqual(prepared_payload["items"][0]["item_type"], "BIE")

    def test_packaging_sale_converts_to_base_units_and_allows_negative_stock(self):
        carton = ConditionnementProduit.objects.create(
            produit=self.product,
            code="POS-FISCAL-C24",
            libelle="Carton de 24",
            facteur_conversion=Decimal("24"),
            prix_vente=Decimal("2000"),
            vendable=True,
            actif=True,
        )
        self._set_stock(10)

        response, _ = self._post_sale(1, conditionnement=carton)
        self.assertEqual(response.status_code, 200, response.content)
        line = Commande.objects.get(pk=response.json()["commande_id"]).lignes.get()
        stock = StockPointDeVente.objects.get(point_de_vente=self.pdv, produit=self.product)
        self.assertEqual(line.quantite_physique, Decimal("24.000"))
        self.assertEqual(stock.quantite, Decimal("-14.000"))

    def test_resumed_pending_sale_remains_allowed_when_stock_became_insufficient(self):
        pending_payload = {
            "panier": [{"id": self.product.pk, "qty": 5, "remise": 0}],
            "document_mode": "FV",
            "remise_globale": 0,
            "paiements": [],
            "commentaires": [],
            "totaux": {"total_ht": 500, "total_tva": 80, "total_ttc": 580},
        }
        save_response = self.client.post(
            reverse("facturation:pending-sale-save"),
            data=json.dumps(pending_payload),
            content_type="application/json",
        )
        self.assertEqual(save_response.status_code, 200, save_response.content)
        pending_id = save_response.json()["sale"]["id"]

        self._set_stock(1)
        resume_response = self.client.post(
            reverse("facturation:pending-sale-resume", args=[pending_id])
        )
        self.assertEqual(resume_response.status_code, 200, resume_response.content)

        response, _ = self._post_sale(5, pending_sale_id=pending_id)
        self.assertEqual(response.status_code, 200, response.content)
        stock = StockPointDeVente.objects.get(point_de_vente=self.pdv, produit=self.product)
        pending_sale = PendingSale.objects.get(pk=pending_id)
        self.assertEqual(stock.quantite, Decimal("-4.000"))
        self.assertEqual(pending_sale.statut, PendingSale.STATUS_VALIDATED)
        self.assertEqual(pending_sale.commande_validee_id, response.json()["commande_id"])
