"""Donnees communes des tests du module restaurant."""

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

from dgi.models import ItemType, TaxGroup
from facturation.models import Categorie, ConditionnementProduit, Configuration, ModePaiement, PointDeVente, Produit, StockPointDeVente

from G_Restaurant.models import DestinationProduit, ImprimanteThermique, ParametresRestaurant, TableRestaurant

FISCALIZE_PATH = "facturation.views.FiscalOrchestrator.fiscalize_commande"
FISCAL_RESULT = {"success": True, "channel": "MCF", "commande_id": 1, "fiscal_transaction_id": "resto-001"}
ENVOYER_PATH = "G_Restaurant.escpos.envoyer"


class RestaurantDataMixin:
    """Restaurant actif : tables, produits Cuisine / Bar / Normal, imprimantes, un utilisateur par role."""

    def setUp(self):
        cache.clear()
        self.pdv = PointDeVente.objects.create(nom="Restaurant Central")
        self.boutique = PointDeVente.objects.create(nom="Boutique")
        ParametresRestaurant.objects.create(point_de_vente=self.pdv, actif=True)
        Configuration.objects.create(taux_change=1, mode_dgi="ttc", type_dgi="FV", nom_entreprise="Chez Test")
        ModePaiement.objects.get_or_create(code="ESPECES", defaults={"designation": "Especes"})
        self.tax, _ = TaxGroup.objects.update_or_create(code="B", defaults={"name": "Taxable 16%", "tax": Decimal("16")})
        self.kind, _ = ItemType.objects.update_or_create(code="BIE", defaults={"name": "Bien"})

        self.admin = self._user("admin-resto", "ADMIN")
        self.serveur = self._user("serveur", "SERVEUR")
        self.caissier = self._user("caissier", "CAISSIER")
        self.caissier2 = self._user("caissier2", "CAISSIER")
        self.cuisinier = self._user("cuisinier", "CUISINIER")
        self.gerant = self._user("gerant", "GERANT")

        plats = Categorie.objects.create(nom="Plats")
        boissons = Categorie.objects.create(nom="Boissons")
        self.poulet = self._produit("Poulet braisé", "PLAT-1", "12000", plats, "CUISINE")
        self.frites = self._produit("Frites", "PLAT-2", "3000", plats, "CUISINE")
        self.biere = self._produit("Bière Primus", "BOI-1", "2500", boissons, "BAR")
        self.eau = self._produit("Eau", "BOI-2", "1000", boissons, "NORMAL")
        StockPointDeVente.objects.create(point_de_vente=self.pdv, produit=self.biere, quantite=Decimal("48"))

        self.table1 = TableRestaurant.objects.create(point_de_vente=self.pdv, numero="1", zone="Salle", couverts=4)
        self.table2 = TableRestaurant.objects.create(point_de_vente=self.pdv, numero="2", zone="Salle", couverts=2)
        self.imp_cuisine = ImprimanteThermique.objects.create(point_de_vente=self.pdv, destination="CUISINE", nom="Epson cuisine",
                                                              type_connexion="RESEAU", adresse_ip="192.168.1.50")
        self.imp_bar = ImprimanteThermique.objects.create(point_de_vente=self.pdv, destination="BAR", nom="Xprinter bar",
                                                          type_connexion="USB", peripherique="/dev/usb/lp0", largeur_papier=58)

    def tearDown(self):
        cache.clear()

    def _user(self, username, role, pdv=None):
        return get_user_model().objects.create_user(username=username, email=f"{username}@resto.test", password="x", role=role,
                                                    point_de_vente=pdv or self.pdv, first_name=username.capitalize())

    def _produit(self, nom, sku, prix, categorie, destination):
        produit = Produit.objects.create(nom=nom, code_sku=sku, prix_vente=Decimal(prix), taxgroup=self.tax, typeart=self.kind,
                                         categorie=categorie)
        DestinationProduit.objects.create(produit=produit, destination=destination)
        return produit

    # ------------------------------------------------------------ actions
    def login(self, user):
        cache.clear()
        self.client.force_login(user)

    def post_json(self, url, data=None):
        return self.client.post(url, data=json.dumps(data or {}), content_type="application/json")

    def ligne(self, produit, qty):
        cond = ConditionnementProduit.objects.get(produit=produit, facteur_conversion=1)
        return {"id": produit.pk, "conditionnement_id": cond.pk, "qty": qty, "remise": 0, "prix": float(produit.prix_vente)}

    def mettre_en_attente(self, panier, table=None, serveur=None, couverts=2, vente_id=None, **extra):
        restaurant = {"table_id": table.pk if table else None, "serveur_id": serveur.pk if serveur else None,
                      "couverts": couverts, "observation": extra.pop("observation", ""), "motif": extra.pop("motif", "")}
        with patch(ENVOYER_PATH) as envoyer, self.captureOnCommitCallbacks(execute=True):
            response = self.post_json(reverse("facturation:pending-sale-save"), {
                "pending_sale_id": vente_id, "panier": panier, "document_mode": "FV", "client_id": "", "paiements": [],
                "commentaires": [], "totaux": {"total_ttc": 0}, "restaurant": restaurant, **extra,
            })
        return response, envoyer

    def valider(self, panier, montant, vente_id=None):
        """Validation du POS (Valider & Facturer) avec fiscalisation simulee."""
        with patch(FISCALIZE_PATH, return_value=FISCAL_RESULT), patch(ENVOYER_PATH) as envoyer, \
                self.captureOnCommitCallbacks(execute=True):
            response = self.post_json(reverse("facturation:pos-view"), {
                "pending_sale_id": vente_id, "panier": panier, "document_mode": "FV", "client_id": "", "client_nif": "",
                "remise_globale": 0, "commentaires": [],
                "paiements": [{"montant_verse": float(montant), "devise": "CDF", "mode": "ESPECES", "taux": 1}],
            })
        return response, envoyer


class RestaurantTestCase(RestaurantDataMixin, TestCase):
    """Cas de test standard."""
