"""Tests automatises de l'application stock."""

from decimal import Decimal
from io import BytesIO
from unittest import skipUnless
from unittest.mock import patch

from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import SimpleTestCase, TestCase
from django.urls import reverse

from facturation.models import (
    PermissionBouton,
    PointDeVente,
    Produit,
    ProduitPointVentePrix,
    StockPointDeVente,
)
from facturation.ui_permissions import get_user_ui_permissions

from .forms import StockCreateForm as BaseStockCreateForm
from .forms import StockForm as BaseStockForm
from .views import (
    StockCreateView as BaseStockCreateView,
    StockListView as BaseStockListView,
    StockUpdateView as BaseStockUpdateView,
    get_prix_pdv as base_get_prix_pdv,
    produits_par_pdv as base_produits_par_pdv,
)

try:
    from openpyxl import Workbook, load_workbook
except ImportError:  # pragma: no cover - depend de l'environnement local.
    Workbook = None
    load_workbook = None


class StockRoutingTests(SimpleTestCase):
    """Regroupe les tests lies aux routes publiques du stock."""

    def test_facturation_stock_routes_keep_public_paths(self):
        """Verifie que les routes publiques du stock restent stables."""

        self.assertEqual(reverse("facturation:stock-list"), "/stocks/")
        self.assertEqual(reverse("facturation:stock-create"), "/stocks/creer/")
        self.assertEqual(reverse("facturation:stock-prix-pdv"), "/api/prix-pdv/")
        self.assertEqual(reverse("facturation:stock-produits-par-pdv"), "/stocks/api/produits-par-pdv/")
        self.assertEqual(reverse("facturation:stock-excel-template"), "/stocks/excel/modele/")
        self.assertEqual(reverse("facturation:stock-excel-import"), "/stocks/excel/importer/")
        self.assertEqual(reverse("facturation:stock-export-excel", args=[1]), "/stocks/export/excel/1/")
        self.assertEqual(reverse("facturation:stock-update", args=[1]), "/stocks/1/modifier/")


class StockCompatibilityTests(SimpleTestCase):
    """Regroupe les tests lies a la compatibilite des imports de stock."""

    def test_facturation_reexports_stock_forms_and_views(self):
        """Verifie que facturation reexporte toujours les composants stock."""

        from facturation.forms import StockCreateForm as FacturationStockCreateForm
        from facturation.forms import StockForm as FacturationStockForm
        from facturation.views import (
            StockCreateView as FacturationStockCreateView,
            StockListView as FacturationStockListView,
            StockUpdateView as FacturationStockUpdateView,
            get_prix_pdv as facturation_get_prix_pdv,
            produits_par_pdv as facturation_produits_par_pdv,
        )

        self.assertIs(FacturationStockForm, BaseStockForm)
        self.assertIs(FacturationStockCreateForm, BaseStockCreateForm)
        self.assertIs(FacturationStockListView, BaseStockListView)
        self.assertIs(FacturationStockCreateView, BaseStockCreateView)
        self.assertIs(FacturationStockUpdateView, BaseStockUpdateView)
        self.assertIs(facturation_get_prix_pdv, base_get_prix_pdv)
        self.assertIs(facturation_produits_par_pdv, base_produits_par_pdv)


class StockEndpointsTests(TestCase):
    """Regroupe les tests lies aux ecrans et comportements du module stock."""

    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        cache.clear()
        self.point_de_vente = PointDeVente.objects.create(nom="PDV Stock App")
        self.admin_user = get_user_model().objects.create_user(
            username="admin-stock-app",
            email="admin-stock-app@test.com",
            password="secret123",
            role="ADMIN",
            is_staff=True,
            point_de_vente=self.point_de_vente,
        )
        self.client.force_login(self.admin_user)
        self.produit = Produit.objects.create(
            nom="Produit Stock App",
            code_sku="STOCK-APP-001",
            prix_vente=Decimal("1000.00"),
            actif=True,
        )
        self.second_produit = Produit.objects.create(
            nom="Produit Stock App Deux",
            code_sku="STOCK-APP-002",
            prix_vente=Decimal("2500.00"),
            actif=True,
        )
        self.stock = StockPointDeVente.objects.create(
            point_de_vente=self.point_de_vente,
            produit=self.produit,
            quantite=Decimal("10.000"),
            prix_vente=Decimal("1200.00"),
            seuil_alerte=2,
        )

    @staticmethod
    def _message_texts(response):
        """Extrait les messages Django rendus dans la reponse finale."""

        return [str(message) for message in response.context["messages"]]

    @staticmethod
    def _set_stock_ui_permission(bouton, autorise=True, role="ADMIN"):
        """Cree une permission UI Stocks explicite pour le role donne."""

        PermissionBouton.objects.update_or_create(
            module="stocks",
            bouton=bouton,
            role=role,
            defaults={"label": bouton, "autorise": autorise},
        )

    def _allow_sensitive_stock_price_fields(self):
        """Autorise explicitement les champs financiers Stocks pour ce scenario."""

        for bouton in ("show_purchase_price_field", "show_sale_price_pdv_field"):
            self._set_stock_ui_permission(bouton, True)

    def test_stock_pages_still_render(self):
        """Verifie que les ecrans du stock restent accessibles et rendus."""

        self._allow_sensitive_stock_price_fields()

        list_response = self.client.get(reverse("facturation:stock-list"))
        create_response = self.client.get(reverse("facturation:stock-create"))
        update_response = self.client.get(reverse("facturation:stock-update", args=[self.stock.pk]))

        self.assertEqual(list_response.status_code, 200)
        self.assertEqual(create_response.status_code, 200)
        self.assertEqual(update_response.status_code, 200)
        self.assertTemplateUsed(list_response, "stock/stock_list.html")
        self.assertTemplateUsed(create_response, "stock/stock_create.html")
        self.assertTemplateUsed(update_response, "stock/stock_form.html")
        self.assertContains(create_response, "Ajouter une ligne")
        self.assertContains(create_response, "Total général")
        self.assertContains(create_response, "Télécharger le modèle")
        self.assertContains(create_response, "Importer un fichier Excel")
        self.assertContains(create_response, "Exporter le stock actuel")
        self.assertContains(create_response, "Tout sélectionner")
        self.assertContains(create_response, "Quantité à appliquer aux articles sélectionnés")
        self.assertContains(create_response, "Prix unitaire (achat)")
        self.assertContains(create_response, "Prix de vente PDV (optionnel)")
        self.assertIn("stock_ui_permissions", create_response.context)

    def test_stock_create_hides_sensitive_price_fields_without_ui_override(self):
        """Les prix sensibles du stock restent masques sans autorisation UI explicite."""

        response = self.client.get(reverse("facturation:stock-create"))

        self.assertEqual(response.status_code, 200)
        self.assertFalse(response.context["stock_ui_permissions"]["show_purchase_price_field"])
        self.assertFalse(response.context["stock_ui_permissions"]["show_sale_price_pdv_field"])
        self.assertNotContains(response, "Prix unitaire (achat)")
        self.assertNotContains(response, "Prix de vente PDV (optionnel)")
        self.assertNotContains(response, 'name="lignes-0-prix_unitaire"', html=False)
        self.assertNotContains(response, 'name="lignes-0-prix_vente_pdv"', html=False)
        self.assertNotContains(response, 'name="lignes-__prefix__-prix_unitaire"', html=False)
        self.assertNotContains(response, 'name="lignes-__prefix__-prix_vente_pdv"', html=False)

    def test_stock_create_reads_ui_permissions_once(self):
        """La vue Stocks injecte une seule map UI sans multiplier les appels template."""

        with patch("stock.views.get_user_ui_permissions", wraps=get_user_ui_permissions) as mocked:
            response = self.client.get(reverse("facturation:stock-create"))

        self.assertEqual(response.status_code, 200)
        self.assertIn("stock_ui_permissions", response.context)
        self.assertEqual(mocked.call_count, 1)
        self.assertEqual(mocked.call_args.args[1], "stocks")

    def test_stock_ui_overrides_hide_create_controls(self):
        """Les overrides UI masquent seulement les controles, pas les routes backend."""

        for bouton in (
            "show_import_button",
            "show_export_button",
            "show_bulk_apply_quantity",
            "show_delete_line_button",
            "show_restock_button",
        ):
            self._set_stock_ui_permission(bouton, False)

        create_response = self.client.get(reverse("facturation:stock-create"))
        list_response = self.client.get(reverse("facturation:stock-list"))

        self.assertEqual(create_response.status_code, 200)
        self.assertEqual(list_response.status_code, 200)
        self.assertNotContains(create_response, "Importer un fichier Excel")
        self.assertNotContains(create_response, "Exporter le stock actuel")
        self.assertNotContains(
            create_response,
            'for="stock-select-all">Tout sélectionner',
            html=False,
        )
        self.assertNotContains(create_response, "Sélectionner cette ligne")
        self.assertNotContains(create_response, 'title="Supprimer la ligne"', html=False)
        self.assertNotContains(list_response, "Reapprovisionner / creer")

    def test_stock_create_saves_multi_line_replenishment_batch(self):
        """Verifie que le lot ajoute l'existant et cree les nouvelles lignes."""

        response = self.client.post(
            reverse("facturation:stock-create"),
            {
                "point_de_vente": self.point_de_vente.pk,
                "lignes-TOTAL_FORMS": "2",
                "lignes-INITIAL_FORMS": "0",
                "lignes-MIN_NUM_FORMS": "0",
                "lignes-MAX_NUM_FORMS": "1000",
                "lignes-0-produit": self.produit.pk,
                "lignes-0-produit_label": "Produit Stock App (STOCK-APP-001)",
                "lignes-0-quantite": "5.000",
                "lignes-0-prix_unitaire": "1000.00",
                "lignes-0-prix_vente_pdv": "1250.00",
                "lignes-1-produit": self.second_produit.pk,
                "lignes-1-produit_label": "Produit Stock App Deux (STOCK-APP-002)",
                "lignes-1-quantite": "3.250",
                "lignes-1-prix_unitaire": "2500.00",
                "lignes-1-prix_vente_pdv": "2750.00",
            },
            follow=True,
        )

        self.assertEqual(response.status_code, 200)
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("15.000"))
        self.assertEqual(self.stock.prix_vente, Decimal("1250.00"))
        created_stock = StockPointDeVente.objects.get(
            point_de_vente=self.point_de_vente,
            produit=self.second_produit,
        )
        self.assertEqual(created_stock.quantite, Decimal("3.250"))
        self.assertEqual(created_stock.prix_vente, Decimal("2750.00"))
        self.assertEqual(
            ProduitPointVentePrix.objects.get(
                point_de_vente=self.point_de_vente,
                produit=self.produit,
            ).prix_vente,
            Decimal("1250.00"),
        )
        self.assertEqual(
            ProduitPointVentePrix.objects.get(
                point_de_vente=self.point_de_vente,
                produit=self.second_produit,
            ).prix_vente,
            Decimal("2750.00"),
        )
        self.assertTrue(
            any(
                message.startswith("Le réapprovisionnement du stock a été enregistré avec succès")
                for message in self._message_texts(response)
            )
        )

    def test_stock_create_preserves_existing_sale_price_when_blank(self):
        """Verifie qu'un prix PDV vide ne remplace pas le prix existant."""

        response = self.client.post(
            reverse("facturation:stock-create"),
            {
                "point_de_vente": self.point_de_vente.pk,
                "lignes-TOTAL_FORMS": "1",
                "lignes-INITIAL_FORMS": "0",
                "lignes-MIN_NUM_FORMS": "0",
                "lignes-MAX_NUM_FORMS": "1000",
                "lignes-0-produit": self.produit.pk,
                "lignes-0-produit_label": "Produit Stock App (STOCK-APP-001)",
                "lignes-0-quantite": "2.000",
                "lignes-0-prix_unitaire": "1000.00",
                "lignes-0-prix_vente_pdv": "",
            },
            follow=True,
        )

        self.assertEqual(response.status_code, 200)
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("12.000"))
        self.assertEqual(self.stock.prix_vente, Decimal("1200.00"))
        self.assertFalse(
            ProduitPointVentePrix.objects.filter(
                point_de_vente=self.point_de_vente,
                produit=self.produit,
            ).exists()
        )

    def test_stock_create_allows_new_stock_without_sale_price(self):
        """Verifie qu'une nouvelle ligne stock peut etre creee sans prix PDV."""

        response = self.client.post(
            reverse("facturation:stock-create"),
            {
                "point_de_vente": self.point_de_vente.pk,
                "lignes-TOTAL_FORMS": "1",
                "lignes-INITIAL_FORMS": "0",
                "lignes-MIN_NUM_FORMS": "0",
                "lignes-MAX_NUM_FORMS": "1000",
                "lignes-0-produit": self.second_produit.pk,
                "lignes-0-produit_label": "Produit Stock App Deux (STOCK-APP-002)",
                "lignes-0-quantite": "3.000",
                "lignes-0-prix_unitaire": "2500.00",
                "lignes-0-prix_vente_pdv": "",
            },
            follow=True,
        )

        self.assertEqual(response.status_code, 200)
        created_stock = StockPointDeVente.objects.get(
            point_de_vente=self.point_de_vente,
            produit=self.second_produit,
        )
        self.assertEqual(created_stock.quantite, Decimal("3.000"))
        self.assertIsNone(created_stock.prix_vente)
        self.assertFalse(
            ProduitPointVentePrix.objects.filter(
                point_de_vente=self.point_de_vente,
                produit=self.second_produit,
            ).exists()
        )

    def test_products_api_supports_stock_autocomplete_query(self):
        """Verifie le JSON consomme par l'autocomplete produit du stock."""

        response = self.client.get("/api/produits/", {"q": "Stock App"})

        self.assertEqual(response.status_code, 200)
        payload = response.json()
        items = payload if isinstance(payload, list) else payload.get("results", [])
        matching = [item for item in items if item["id"] == self.produit.id]
        self.assertTrue(matching)
        self.assertIn("prix_vente", matching[0])
        self.assertIn("prix_achat", matching[0])
        self.assertEqual(matching[0]["prix_achat"], 1000.0)

        short_query_response = self.client.get("/api/produits/", {"q": "S"})
        self.assertEqual(short_query_response.status_code, 200)
        short_payload = short_query_response.json()
        self.assertEqual(short_payload if isinstance(short_payload, list) else short_payload.get("results", []), [])

    def test_prix_pdv_api_returns_purchase_and_pdv_sale_price(self):
        """Verifie le JSON de pre-remplissage des prix pour le reapprovisionnement."""

        existing_response = self.client.get(
            reverse("facturation:stock-prix-pdv"),
            {"produit_id": self.produit.pk, "pdv_id": self.point_de_vente.pk},
        )

        self.assertEqual(existing_response.status_code, 200)
        existing_payload = existing_response.json()
        self.assertTrue(existing_payload["existe"])
        self.assertEqual(existing_payload["prix_achat"], 1000.0)
        self.assertEqual(existing_payload["prix_vente"], 1200.0)
        self.assertEqual(existing_payload["quantite_actuelle"], 10)

        new_response = self.client.get(
            reverse("facturation:stock-prix-pdv"),
            {"produit_id": self.second_produit.pk, "pdv_id": self.point_de_vente.pk},
        )

        self.assertEqual(new_response.status_code, 200)
        new_payload = new_response.json()
        self.assertFalse(new_payload["existe"])
        self.assertEqual(new_payload["prix_achat"], 2500.0)
        self.assertIsNone(new_payload["prix_vente"])
        self.assertEqual(new_payload["quantite_actuelle"], 0)

    def test_products_by_pdv_api_returns_existing_stock_lines(self):
        """Verifie le chargement AJAX des produits deja en stock pour un PDV."""

        StockPointDeVente.objects.create(
            point_de_vente=self.point_de_vente,
            produit=self.second_produit,
            quantite=Decimal("5.000"),
            prix_vente=None,
        )

        response = self.client.get(
            reverse("facturation:stock-produits-par-pdv"),
            {"pdv_id": self.point_de_vente.pk},
        )

        self.assertEqual(response.status_code, 200)
        payload = response.json()
        self.assertEqual(len(payload), 2)
        first_line = payload[0]
        second_line = payload[1]
        self.assertEqual(first_line["produit_id"], self.produit.pk)
        self.assertEqual(first_line["produit_nom"], "Produit Stock App")
        self.assertEqual(first_line["stock_actuel"], 10)
        self.assertEqual(first_line["prix_achat"], "1000.00")
        self.assertEqual(first_line["prix_vente"], "1200.00")
        self.assertEqual(second_line["produit_id"], self.second_produit.pk)
        self.assertEqual(second_line["stock_actuel"], 5)
        self.assertEqual(second_line["prix_vente"], "")

    @skipUnless(Workbook is not None, "openpyxl n'est pas installe dans cet environnement.")
    def test_stock_excel_template_downloads_expected_columns(self):
        """Verifie le modele Excel de reapprovisionnement stock."""

        response = self.client.get(reverse("facturation:stock-excel-template"))

        self.assertEqual(response.status_code, 200)
        self.assertIn("spreadsheetml", response["Content-Type"])
        self.assertIn("modele_reapprovisionnement_stock.xlsx", response["Content-Disposition"])

        workbook = load_workbook(BytesIO(response.content), read_only=True)
        try:
            worksheet = workbook.active
            headers = [cell.value for cell in next(worksheet.iter_rows(max_row=1))]
            sample = [cell.value for cell in next(worksheet.iter_rows(min_row=2, max_row=2))]
            self.assertEqual(headers, ["nom_produit", "quantite", "prix_vente_pdv"])
            self.assertEqual(sample, ["Exemple Produit", 10, 2500])
        finally:
            workbook.close()

    @skipUnless(Workbook is not None, "openpyxl n'est pas installe dans cet environnement.")
    def test_stock_excel_import_returns_valid_lines_and_errors(self):
        """Verifie l'import Excel JSON avec badges Ajout/Nouveau."""

        workbook = Workbook()
        worksheet = workbook.active
        worksheet.append(["nom_produit", "quantite", "prix_vente_pdv"])
        worksheet.append(["Produit Stock App", "2.500", "1250"])
        worksheet.append(["Produit Stock App Deux", 4, "2750"])
        worksheet.append(["Produit Inconnu", 1, 100])
        output = BytesIO()
        workbook.save(output)
        workbook.close()
        upload = SimpleUploadedFile(
            "stock.xlsx",
            output.getvalue(),
            content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        )

        response = self.client.post(
            reverse("facturation:stock-excel-import"),
            {"fichier": upload, "pdv_id": str(self.point_de_vente.pk)},
        )

        self.assertEqual(response.status_code, 200)
        payload = response.json()
        self.assertEqual(len(payload["lignes"]), 2)
        self.assertEqual(payload["lignes"][0]["produit_id"], self.produit.pk)
        self.assertEqual(payload["lignes"][0]["prix_vente_pdv"], "1250")
        self.assertEqual(payload["lignes"][1]["produit_id"], self.second_produit.pk)
        self.assertEqual(payload["lignes"][1]["prix_vente_pdv"], "2750")
        self.assertEqual(payload["erreurs"][0]["ligne"], 4)

    @skipUnless(Workbook is not None, "openpyxl n'est pas installe dans cet environnement.")
    def test_stock_excel_import_accepts_missing_sale_price(self):
        """Verifie qu'une ligne Excel produit + quantite suffit au reapprovisionnement."""

        workbook = Workbook()
        worksheet = workbook.active
        worksheet.append(["nom_produit", "quantite", "prix_vente_pdv"])
        worksheet.append(["Produit Stock App Deux", "6.000", None])
        output = BytesIO()
        workbook.save(output)
        workbook.close()
        output.seek(0)

        response = self.client.post(
            reverse("facturation:stock-excel-import"),
            {
                "pdv_id": self.point_de_vente.pk,
                "fichier": SimpleUploadedFile(
                    "stock-sans-prix.xlsx",
                    output.read(),
                    content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                ),
            },
        )

        self.assertEqual(response.status_code, 200)
        payload = response.json()
        self.assertEqual(payload["erreurs"], [])
        self.assertEqual(len(payload["lignes"]), 1)
        self.assertEqual(payload["lignes"][0]["produit_id"], self.second_produit.pk)
        self.assertEqual(payload["lignes"][0]["quantite"], "6.000")
        self.assertEqual(payload["lignes"][0]["prix_vente_pdv"], "")

    @skipUnless(Workbook is not None, "openpyxl n'est pas installe dans cet environnement.")
    def test_stock_excel_export_current_pdv_stock(self):
        """Verifie l'export Excel du stock courant d'un point de vente."""

        response = self.client.get(reverse("facturation:stock-export-excel", args=[self.point_de_vente.pk]))

        self.assertEqual(response.status_code, 200)
        self.assertIn("spreadsheetml", response["Content-Type"])
        self.assertIn("stock_PDV_Stock_App.xlsx", response["Content-Disposition"])

        workbook = load_workbook(BytesIO(response.content), read_only=True)
        try:
            worksheet = workbook.active
            headers = [cell.value for cell in next(worksheet.iter_rows(max_row=1))]
            row = [cell.value for cell in next(worksheet.iter_rows(min_row=2, max_row=2))]
            self.assertEqual(
                headers,
                [
                    "Produit",
                    "Code barre",
                    "Quantité actuelle",
                    "Prix unitaire (achat)",
                    "Prix de vente PDV",
                    "Valeur totale (qte × prix_vente_pdv)",
                ],
            )
            self.assertEqual(row[0], "Produit Stock App")
            self.assertEqual(row[1], "STOCK-APP-001")
            self.assertEqual(row[2], 10)
            self.assertEqual(row[3], 1000)
            self.assertEqual(row[4], 1200)
            self.assertEqual(row[5], 12000)
        finally:
            workbook.close()

    def test_stock_update_displays_success_message(self):
        """Verifie le message de succes apres modification d'une ligne de stock."""

        response = self.client.post(
            reverse("facturation:stock-update", args=[self.stock.pk]),
            {
                "point_de_vente": self.point_de_vente.pk,
                "produit": self.produit.pk,
                "quantite": "12.000",
                "seuil_alerte": "3",
            },
            follow=True,
        )

        self.assertEqual(response.status_code, 200)
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("12.000"))
        self.assertIn(
            "Le mouvement de stock a été modifié avec succès.",
            self._message_texts(response),
        )
