from decimal import Decimal

from django.db.models import Sum
from django.test import TestCase
from django.urls import reverse

from facturation.accounting import accounting_amount_expression, with_accounting_effect
from facturation.fiscal_cancellation import FiscalCancellationService
from facturation.fiscal_exceptions import FiscalBusinessError
from facturation.models import (
    Commande,
    LigneCommande,
    MouvementStock,
    PointDeVente,
    Produit,
    StockPointDeVente,
    User,
)
from facturation.views import _build_commande_history_groups


class CancellationAccountingTests(TestCase):
    """Garantit qu'une annulation neutralise reellement les comptes de vente."""

    def setUp(self):
        self.user = User.objects.create_user(
            username="accounting-cancel",
            email="accounting-cancel@example.com",
            password="secret",
            is_staff=True,
            is_superuser=True,
        )
        self.point = PointDeVente.objects.create(nom="PDV Comptabilite")

    def _document(self, amount, *, invoice_type="FV", cancelled=False, source=None):
        return Commande.objects.create(
            point_de_vente=self.point,
            vendeur=self.user,
            montant_total=Decimal(amount),
            montant_paye=Decimal(amount),
            tva_montant=Decimal("0.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture=invoice_type,
            est_annulee=cancelled,
            facture_origine=source,
            nature_avoir="RAN" if invoice_type in {"FA", "EA"} else None,
        )

    def test_full_credit_note_nets_to_zero_and_partial_credit_reduces_sales(self):
        fully_cancelled = self._document("100.00", cancelled=True)
        self._document("100.00", invoice_type="FA", source=fully_cancelled)

        partly_credited = self._document("100.00")
        partial_credit = self._document("25.00", invoice_type="FA", source=partly_credited)
        partial_credit.nature_avoir = "RRR"
        partial_credit.save(update_fields=["nature_avoir"])

        self._document("80.00", cancelled=True)  # ancienne annulation locale sans avoir

        documents = with_accounting_effect(
            Commande.objects.filter(point_de_vente=self.point).order_by("pk")
        )
        net_total = documents.aggregate(
            total=Sum(accounting_amount_expression("montant_total"))
        )["total"]
        self.assertEqual(net_total, Decimal("75.00"))

        groups, grand_total = _build_commande_history_groups(list(documents))
        self.assertEqual(groups[0]["total"], Decimal("75.00"))
        self.assertEqual(grand_total["total"], Decimal("75.00"))

    def test_local_cancellation_restores_stock_once_and_marks_invoice(self):
        product = Produit.objects.create(
            nom="Article annule localement",
            code_sku="LOCAL-CANCEL-1",
            prix_vente=Decimal("10.00"),
        )
        stock = StockPointDeVente.objects.create(
            point_de_vente=self.point,
            produit=product,
            quantite=Decimal("4.000"),
        )
        invoice = self._document("10.00")
        LigneCommande.objects.create(
            commande=invoice,
            produit=product,
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("10.00"),
            remise=Decimal("0.00"),
        )

        result = FiscalCancellationService().cancel_commande(
            invoice,
            "Erreur de saisie",
            self.user,
        )

        invoice.refresh_from_db()
        stock.refresh_from_db()
        self.assertTrue(result["success"])
        self.assertTrue(invoice.est_annulee)
        self.assertEqual(stock.quantite, Decimal("5.000"))
        self.assertEqual(
            MouvementStock.objects.filter(
                commande_associee=invoice,
                type_mouvement=MouvementStock.TYPE_ANNULATION_VENTE,
            ).count(),
            1,
        )

        with self.assertRaisesMessage(FiscalBusinessError, "deja annulee"):
            FiscalCancellationService().cancel_commande(
                invoice,
                "Deuxieme tentative",
                self.user,
            )
        stock.refresh_from_db()
        self.assertEqual(stock.quantite, Decimal("5.000"))

    def test_invoice_history_mentions_cancelled_even_beside_invoice_number(self):
        cancelled = self._document("80.00", cancelled=True)
        self.client.force_login(self.user)

        response = self.client.get(reverse("facturation:commande-list"))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, cancelled.numero)
        self.assertContains(response, "ANNULÉE", count=2)
