"""Un même achat peut être réparti entre plusieurs dépôts autorisés."""
from decimal import Decimal

from django.conf import settings
from django.core.exceptions import ValidationError
from django.urls import reverse

from facturation.models import PointDeVente, StockPointDeVente
from paiements.services import achats_accessibles, get_soldes_fournisseur

from .forms import AchatForm, ReceptionAchatForm
from .models import Achat, LigneReceptionAchat, ReceptionAchat, RetourFournisseur, LigneRetourFournisseur
from .tests import AchatTestBase


class AchatDestinationsTests(AchatTestBase):
    def setUp(self):
        super().setUp()
        self.other = PointDeVente.objects.create(nom="Deuxième dépôt")
        self.outside = PointDeVente.objects.create(nom="Dépôt non autorisé")
        self.inactive = PointDeVente.objects.create(nom="Dépôt inactif", actif=False)
        self.client.force_login(self.user)

    def payload(self, points=None):
        return {
            "fournisseur": self.fournisseur.pk,
            "points_de_vente": points if points is not None else [self.pdv.pk, self.other.pk],
            "date_achat": "2026-09-16", "devise": "CDF", "mode_prix": "HT",
            "taux_change": "1", "remise_globale": "0",
            "lignes-TOTAL_FORMS": "1", "lignes-INITIAL_FORMS": "0",
            "lignes-0-produit": self.produit.pk,
            "lignes-0-conditionnement": self.carton.pk,
            "lignes-0-quantite": "10", "lignes-0-prix_achat_conditionnement": "15600",
            "lignes-0-remise": "0",
        }

    def multi_purchase(self):
        purchase = self.create_achat()
        purchase.points_de_vente.set([self.pdv, self.other])
        line = self.create_line(purchase)
        return purchase, line

    def secondary_receipt(self):
        purchase, line = self.multi_purchase()
        purchase.valider()
        receipt = ReceptionAchat.objects.create(achat=purchase, point_de_vente=self.other)
        received = LigneReceptionAchat.objects.create(
            reception=receipt, ligne_achat=line, quantite_commerciale_recue=4,
        )
        receipt.valider(user=self.user)
        received.refresh_from_db()
        return purchase, line, receipt, received

    def test_create_persists_one_invoice_and_multiple_destinations(self):
        response = self.client.post(reverse("facturation:achat-create"), self.payload())
        self.assertEqual(response.status_code, 302)
        purchase = Achat.objects.get()
        self.assertSetEqual(set(purchase.destinations.values_list("pk", flat=True)), {self.pdv.pk, self.other.pk})
        self.assertEqual(purchase.lignes.count(), 1)
        self.assertEqual(purchase.total_net, Decimal("156000"))
        detail = self.client.get(reverse("facturation:achat-detail", args=[purchase.pk]))
        self.assertContains(detail, self.other.nom)
        filtered = self.client.get(reverse("facturation:achat-list"), {"point_de_vente": self.other.pk})
        self.assertEqual(list(filtered.context["achats"]), [purchase])

    def test_all_points_respects_user_scope_and_active_status(self):
        self.vendor.points_de_vente.set([self.pdv, self.other, self.inactive])
        payload = self.payload([])
        payload["tous_points_de_vente"] = "on"
        form = AchatForm(data=payload, user=self.vendor)
        self.assertTrue(form.is_valid(), form.errors)
        purchase = form.save()
        self.assertSetEqual(set(purchase.destinations.values_list("pk", flat=True)), {self.pdv.pk, self.other.pk})

    def test_empty_unauthorized_and_inactive_destinations_are_rejected(self):
        for points in ([], [self.outside.pk], [self.inactive.pk]):
            with self.subTest(points=points):
                form = AchatForm(data=self.payload(points), user=self.vendor)
                self.assertFalse(form.is_valid())
                self.assertIn("points_de_vente", form.errors)

    def test_edit_preserves_then_replaces_destinations(self):
        purchase, line = self.multi_purchase()
        response = self.client.get(reverse("facturation:achat-update", args=[purchase.pk]))
        self.assertSetEqual(set(response.context["form"]["points_de_vente"].value()), {self.pdv.pk, self.other.pk})
        payload = self.payload([self.other.pk])
        payload.update({"lignes-INITIAL_FORMS": "1", "lignes-0-id": line.pk})
        response = self.client.post(reverse("facturation:achat-update", args=[purchase.pk]), payload)
        self.assertEqual(response.status_code, 302)
        purchase.refresh_from_db()
        self.assertEqual(list(purchase.destinations), [self.other])
        self.assertEqual(purchase.point_de_vente, self.other)

    def test_error_preserves_selected_destinations_and_english_labels(self):
        self.client.cookies[settings.LANGUAGE_COOKIE_NAME] = "en"
        payload = self.payload()
        payload["lignes-0-quantite"] = "-1"
        response = self.client.post(reverse("facturation:achat-create"), payload)
        self.assertSetEqual(set(map(int, response.context["form"]["points_de_vente"].value())), {self.pdv.pk, self.other.pk})
        for text in ("New supplier purchase", "Destination points of sale / warehouses", "All points of sale", "Supplier invoice date", "Exchange rate", "Supplier information", "Save draft"):
            self.assertContains(response, text)

    def test_financial_scope_counts_one_invoice_once_for_several_points(self):
        purchase, _ = self.multi_purchase()
        purchase.valider()
        self.vendor.points_de_vente.set([self.other])
        self.assertEqual(list(achats_accessibles(self.vendor)), [purchase])
        summary = next(row for row in get_soldes_fournisseur(self.fournisseur, self.user) if row["devise"] == "CDF")
        self.assertEqual(summary["total_achats"], Decimal("156000"))
        self.assertEqual(summary["dette_nette"], Decimal("156000"))

    def test_restricted_user_cannot_drop_other_destinations_when_editing(self):
        purchase, _ = self.multi_purchase()
        form = AchatForm(data=self.payload([self.pdv.pk]), instance=purchase, user=self.vendor)
        self.assertFalse(form.is_valid())
        self.assertIn("points_de_vente", form.errors)

    def test_validated_destinations_are_locked_and_inactive_points_block_validation(self):
        purchase, _ = self.multi_purchase()
        PointDeVente.objects.filter(pk=self.other.pk).update(actif=False)
        with self.assertRaises(ValidationError):
            purchase.valider()
        PointDeVente.objects.filter(pk=self.other.pk).update(actif=True)
        purchase.valider()
        with self.assertRaises(ValidationError):
            purchase.points_de_vente.remove(self.other)

    def test_inactive_existing_primary_destination_is_reported_on_the_multiple_field(self):
        purchase, _ = self.multi_purchase()
        PointDeVente.objects.filter(pk=self.pdv.pk).update(actif=False)
        purchase.refresh_from_db()
        form = AchatForm(data=self.payload(), instance=purchase, user=self.user)
        self.assertFalse(form.is_valid())
        self.assertIn("points_de_vente", form.errors)

    def test_purchase_reports_match_secondary_destination_without_double_counting(self):
        from rapports.gestion_services import build_report

        purchase, _ = self.multi_purchase()
        purchase.valider()
        for filters in ({}, {"pdv": self.other}):
            report = build_report("achats", self.user, filters)
            self.assertEqual(report.queryset.count(), 1)
            self.assertEqual(report.totals[0]["achats"], Decimal("156000"))

    def test_secondary_receipt_updates_its_stock_and_shared_remaining_quantity(self):
        purchase, line, _, _ = self.secondary_receipt()
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("100"))
        self.assertEqual(StockPointDeVente.objects.get(point_de_vente=self.other, produit=self.produit).quantite, Decimal("96"))
        self.assertEqual(line.reste_a_recevoir, Decimal("6"))
        receipt = ReceptionAchat.objects.create(achat=purchase, point_de_vente=self.pdv)
        excess = LigneReceptionAchat.objects.create(reception=receipt, ligne_achat=line, quantite_commerciale_recue=6)
        LigneReceptionAchat.objects.filter(pk=excess.pk).update(quantite_commerciale_recue=7)
        with self.assertRaises(ValidationError):
            receipt.valider()
        with self.assertRaises(ValidationError):
            ReceptionAchat.objects.create(achat=purchase, point_de_vente=self.outside)

    def test_receipt_form_limits_choice_to_accessible_purchase_destinations(self):
        purchase, _ = self.multi_purchase()
        purchase.valider()
        form = ReceptionAchatForm(achat=purchase, user=self.user)
        self.assertSetEqual(set(form.fields["point_de_vente"].queryset), {self.pdv, self.other})
        self.vendor.points_de_vente.set([self.other])
        form = ReceptionAchatForm(data={"date_reception": "2026-09-18"}, achat=purchase, user=self.vendor)
        self.assertTrue(form.is_valid(), form.errors)
        self.assertEqual(form.cleaned_data["point_de_vente"], self.other)

    def test_supplier_return_uses_secondary_receipt_stock(self):
        purchase, _, _, source = self.secondary_receipt()
        supplier_return = RetourFournisseur.objects.create(achat=purchase, point_de_vente=self.other, motif="DEFECTUEUX", created_by=self.user)
        LigneRetourFournisseur.objects.create(retour=supplier_return, ligne_reception=source, quantite_commerciale=1)
        supplier_return.valider(user=self.user)
        self.assertEqual(StockPointDeVente.objects.get(point_de_vente=self.other, produit=self.produit).quantite, Decimal("72"))
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("100"))
