﻿"""Tests automatises de l'application dashboard."""

from decimal import Decimal

from django.contrib.auth import get_user_model
from django.test import SimpleTestCase, TestCase
from django.urls import reverse

from facturation.models import Client, Commande, Configuration, LigneCommande, PointDeVente, Produit, UserMenuPermission


class DashboardRoutingTests(SimpleTestCase):
    """Regroupe les tests des routes publiques du dashboard."""


    def test_dashboard_route_keeps_historical_facturation_namespace(self):
        """Verifie que la route du dashboard conserve l'espace de noms historique de facturation."""

        self.assertEqual(reverse("facturation:dashboard"), "/")

    def test_dashboard_api_route_keeps_historical_public_path(self):
        """Verifie que la route API du dashboard conserve son chemin public historique."""

        self.assertEqual(reverse("api_dashboard"), "/api/dashboard/")


class DashboardEndpointsTests(TestCase):
    """Regroupe les tests des ecrans et endpoints du dashboard."""


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

        self.point_de_vente = PointDeVente.objects.create(nom="PDV Dashboard")
        self.autre_point_de_vente = PointDeVente.objects.create(nom="PDV Masque")
        self.user = get_user_model().objects.create_user(
            username="dashboard-user",
            email="dashboard-user@test.com",
            password="secret123",
            point_de_vente=self.point_de_vente,
        )
        UserMenuPermission.objects.create(
            user=self.user,
            permission_key="dashboard_export",
            is_allowed=True,
        )
        self.autre_user = get_user_model().objects.create_user(
            username="dashboard-other-user",
            email="dashboard-other-user@test.com",
            password="secret123",
            point_de_vente=self.autre_point_de_vente,
        )
        self.customer = Client.objects.create(nom_complet="Client Dashboard")
        self.product = Produit.objects.create(
            nom="Produit Dashboard",
            code_sku="DASH-001",
            prix_vente=Decimal("1000.00"),
            unite_mesure="U",
        )
        Configuration.objects.create(taux_change=Decimal("2800.00"))
        self.client.force_login(self.user)

    def _create_invoice(self, *, point_de_vente=None, vendeur=None, client=None, total="1180.00", tva="180.00"):
        """Cree une facture et une ligne pour tester le detail CA PDV."""

        commande = Commande.objects.create(
            point_de_vente=point_de_vente or self.point_de_vente,
            vendeur=vendeur or self.user,
            client=client if client is not None else self.customer,
            montant_total=Decimal(total),
            montant_paye=Decimal(total),
            tva_montant=Decimal(tva),
            type_facture="FV",
        )
        LigneCommande.objects.create(
            commande=commande,
            produit=self.product,
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("1000.00"),
        )
        return commande

    def test_dashboard_page_still_renders(self):
        """Verifie que la page du dashboard reste accessible et correctement rendue."""

        response = self.client.get(reverse("facturation:dashboard"))

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "dashboard/dashboard.html")
        self.assertContains(response, "Détail par point de vente")

    def test_dashboard_does_not_render_mcf_sync_alert(self):
        """Verifie que l'alerte de synchronisation MCF reste absente du dashboard."""

        response = self.client.get(reverse("facturation:dashboard"))

        self.assertNotContains(response, "Synchronisation DGI du MCF")
        self.assertNotIn("mcf_sync_status", response.context)

    def test_dashboard_api_still_returns_expected_sections(self):
        """Verifie que l'API du dashboard retourne toujours les sections attendues."""

        response = self.client.get(reverse("api_dashboard"))

        self.assertEqual(response.status_code, 200)
        payload = response.json()
        self.assertIn("config", payload)
        self.assertIn("user_info", payload)
        self.assertIn("stats", payload)
        self.assertIn("recent_transactions", payload)

    def test_ca_detail_limits_points_de_vente_to_user_scope(self):
        """Verifie qu'un vendeur ne voit que son point de vente dans le detail CA."""

        self._create_invoice()
        self._create_invoice(
            point_de_vente=self.autre_point_de_vente,
            vendeur=self.autre_user,
            total="500.00",
            tva="80.00",
        )

        response = self.client.get(reverse("facturation:dashboard-ca-detail"))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "PDV Dashboard")
        self.assertNotContains(response, "PDV Masque")

    def test_factures_detail_supports_search_pagination_and_dashboard_back(self):
        """Verifie la recherche, la pagination et le retour dashboard des factures."""

        matched_invoice = self._create_invoice()
        matched_invoice.numero = "FV-SEARCH-001"
        matched_invoice.save(update_fields=["numero"])
        other_client = Client.objects.create(nom_complet="Client Facture Pagination")
        for index in range(22):
            self._create_invoice(
                client=other_client,
                total=str(1000 + index),
                tva="0.00",
            )

        detail_url = reverse("facturation:dashboard-factures-detail")
        response = self.client.get(detail_url)

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'class="factures-back-btn"')
        self.assertContains(response, "Rechercher par numéro, client, NIF ou code DGI")
        self.assertTrue(response.context["page_obj"].has_next())
        self.assertEqual(len(response.context["factures"]), 20)

        filtered_response = self.client.get(detail_url, {"q": "SEARCH"})

        self.assertEqual(filtered_response.status_code, 200)
        self.assertEqual(filtered_response.context["filtered_factures_count"], 1)
        self.assertContains(filtered_response, "FV-SEARCH-001")
        self.assertNotContains(filtered_response, "Client Facture Pagination")

    def test_montants_detail_declares_entries_per_page_on_paid_and_unpaid_tables(self):
        """Verifie le selecteur 10 entries per page sur les deux tableaux montants."""

        paid_invoice = self._create_invoice(total="1180.00", tva="180.00")
        Commande.objects.filter(pk=paid_invoice.pk).update(statut_paiement="PAYEE")
        unpaid_invoice = self._create_invoice(total="500.00", tva="80.00")
        Commande.objects.filter(pk=unpaid_invoice.pk).update(
            montant_paye=Decimal("0.00"),
            statut_paiement="IMPAYEE",
        )

        response = self.client.get(reverse("facturation:dashboard-montants-detail"))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Factures payées")
        self.assertContains(response, "Factures impayées")
        self.assertContains(response, "Reste à payer")
        self.assertContains(response, "Taux de paiement")
        self.assertContains(response, "Factures payées / total")
        self.assertContains(response, 'id="resteModal"')
        self.assertEqual(response.context["reste_a_payer_total"], Decimal("500.00"))
        self.assertEqual(response.context["nb_factures_reste"], 1)
        self.assertEqual(response.context["factures_reste_list"].count(), 1)
        self.assertEqual(response.context["factures_reste_list"].first().reste_a_payer_calc, Decimal("500"))
        self.assertContains(response, "Factures avec reste à payer")
        self.assertContains(response, 'class="montants-table datatable"', count=3)
        self.assertContains(response, 'data-per-page="10"', count=3)
        self.assertContains(response, 'data-per-page-select="10,25,50,100"', count=3)

    def test_ventes_jour_detail_can_filter_by_point_de_vente(self):
        """Verifie le detail des ventes du jour et le filtre par point de vente."""

        admin_user = get_user_model().objects.create_user(
            username="dashboard-admin",
            email="dashboard-admin@test.com",
            password="secret123",
            role="ADMIN",
            point_de_vente=self.point_de_vente,
        )
        self.client.force_login(admin_user)
        vente_pdv_principal = self._create_invoice()
        vente_autre_pdv = self._create_invoice(
            point_de_vente=self.autre_point_de_vente,
            vendeur=self.autre_user,
            total="500.00",
            tva="80.00",
        )

        detail_url = reverse("facturation:dashboard-ventes-jour-detail")
        response = self.client.get(detail_url)

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Détail des ventes du jour par point de vente")
        self.assertContains(response, "Répartition par point de vente")
        self.assertContains(response, "PDV Dashboard")
        self.assertContains(response, "PDV Masque")
        self.assertContains(response, vente_pdv_principal.numero)
        self.assertContains(response, vente_autre_pdv.numero)

        filtered_response = self.client.get(
            detail_url,
            {"pdv_id": str(self.autre_point_de_vente.id)},
        )

        self.assertEqual(filtered_response.status_code, 200)
        self.assertEqual(filtered_response.context["nb_ventes"], 1)
        self.assertEqual(filtered_response.context["ca_jour"], Decimal("500.00"))
        self.assertEqual(filtered_response.context["pdv_nom_selected"], "PDV Masque")
        self.assertContains(filtered_response, vente_autre_pdv.numero)
        self.assertNotContains(filtered_response, vente_pdv_principal.numero)

    def test_pdv_detail_renders_summary_filters_and_exports(self):
        """Verifie le detail PDV, le filtre article et les exports Excel/PDF."""

        commande = self._create_invoice()
        detail_url = reverse("facturation:dashboard-pdv-detail", args=[self.point_de_vente.id])

        response = self.client.get(detail_url, {"article_id": self.product.id})

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, commande.numero)
        self.assertContains(response, "Produit Dashboard")
        self.assertEqual(response.context["ca_total"], Decimal("1180.00"))
        self.assertEqual(response.context["ca_ht"], Decimal("1000.00"))

        excel_response = self.client.get(
            reverse("facturation:dashboard-pdv-export-excel", args=[self.point_de_vente.id]),
            {"article_id": self.product.id},
        )
        self.assertEqual(excel_response.status_code, 200)
        self.assertIn("spreadsheetml", excel_response["Content-Type"])

        pdf_response = self.client.get(reverse("facturation:dashboard-pdv-export-pdf", args=[self.point_de_vente.id]))
        self.assertEqual(pdf_response.status_code, 200)
        self.assertEqual(pdf_response["Content-Type"], "application/pdf")

    def test_pdv_detail_blocks_unscoped_point_de_vente(self):
        """Verifie qu'un vendeur ne peut pas ouvrir le detail d'un autre PDV."""

        response = self.client.get(
            reverse("facturation:dashboard-pdv-detail", args=[self.autre_point_de_vente.id])
        )

        self.assertEqual(response.status_code, 404)
