"""Tests de la liste active e-MCF v2 des groupes de taxation A a S."""

from decimal import Decimal
from importlib import import_module
from io import StringIO

from django.apps import apps
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.test import SimpleTestCase, TestCase

from dgi.models import TaxGroup
from dgi.tax_groups import ACTIVE_TAX_GROUP_CODES, RETIRED_TAX_GROUP_CODES, get_tax_group_label
from facturation.forms import ProduitForm, TaxGroupForm
from facturation.models import Commande, LigneCommande, PointDeVente, Produit
from facturation.product_excel import _build_tax_group_cache
from mcf.models import MCFDevice
from mcf.services_mcf import MCFInvoiceService, MCFUnsupportedTaxGroupError


tax_groups_migration = import_module("dgi.migrations.0005_active_tax_groups_q_r_s")
v2_tax_groups_migration = import_module("dgi.migrations.0006_reactivate_tax_groups_l_n_v2")
hors_champ_migration = import_module("facturation.migrations.0059_move_hors_champ_products_to_group_s")

EXPECTED_ACTIVE_CODES = tuple("ABCDEFGHIJKLMNOPQRS")


def migrate_tax_groups():
    """Rejoue la migration des groupes, idempotente, sur la base de test."""

    tax_groups_migration.activate_official_tax_groups(apps, None)
    v2_tax_groups_migration.reactivate_groups(apps, None)


def active_codes():
    """Codes des groupes actifs en base."""

    return tuple(TaxGroup.objects.filter(is_active=True).order_by("code").values_list("code", flat=True))


class TaxGroupReferenceTests(SimpleTestCase):
    """Source de verite des groupes (dgi.tax_groups)."""

    def test_active_list_is_a_to_s(self):
        self.assertEqual(ACTIVE_TAX_GROUP_CODES, EXPECTED_ACTIVE_CODES)
        self.assertEqual(RETIRED_TAX_GROUP_CODES, set("TUVWXYZ"))

    def test_labels_of_renamed_new_and_retired_groups(self):
        self.assertEqual(get_tax_group_label("A"), "GROUPE A (EXONERE)")
        self.assertEqual(get_tax_group_label("Q"), "GROUPE Q (TAXABLE 8%)")
        self.assertEqual(get_tax_group_label("R"), "GROUPE R (TVA MARCHE PUBLIC À FINANCEMENT EXTERIEUR 8%)")
        self.assertEqual(get_tax_group_label("S"), "GROUPE S (HORS CHAMP)")
        # Les factures historiques en L/N gardent un libelle lisible.
        self.assertEqual(get_tax_group_label("L"), "GROUPE L (PRELEVEMENTS SUR VENTES)")
        self.assertEqual(get_tax_group_label("N"), "GROUPE N (TVA SPECIFIQUE)")


class TaxGroupMigrationTests(TestCase):
    """Migration dgi 0005 : groupes actifs, taux, L/N desactives sans perte."""

    def setUp(self):
        migrate_tax_groups()

    def test_expected_groups_are_active_with_official_rates(self):
        self.assertEqual(active_codes(), EXPECTED_ACTIVE_CODES)
        rates = dict(TaxGroup.objects.values_list("code", "tax"))
        for codes, rate in ((("B", "F"), "16.00"), (("C", "G"), "5.00"), (("O", "P"), "1.00"), (("Q", "R"), "8.00"), (("A", "S"), "0.00")):
            for code in codes:
                self.assertEqual(rates[code], Decimal(rate), code)
        self.assertEqual(TaxGroup.objects.get(code="A").name, "GROUPE A (EXONERE)")

    def test_five_and_eight_percent_groups_coexist(self):
        self.assertEqual(
            list(TaxGroup.objects.filter(code__in="CGQR").order_by("code").values_list("code", "tax")),
            [("C", Decimal("5.00")), ("G", Decimal("5.00")), ("Q", Decimal("8.00")), ("R", Decimal("8.00"))],
        )

    def test_existing_database_is_updated_without_duplicates_or_data_loss(self):
        """Base deja remplie : ancien libelle A, L/N utilises, code en minuscule, taux faux."""

        TaxGroup.objects.filter(code="A").update(name="GROUPE A (EXONERE ET HORS CHAMP)", description="ancien")
        TaxGroup.objects.filter(code__in=["Q", "R", "S"]).delete()
        lowercase_q = TaxGroup.objects.create(code="q", name="Saisie manuelle", tax=Decimal("0.00"))
        TaxGroup.objects.filter(code="B").update(tax=Decimal("18.00"))
        TaxGroup.objects.filter(code="D").update(tax=Decimal("3.00"))
        group_l = TaxGroup.objects.get(code="L")
        group_n = TaxGroup.objects.get(code="N")
        produit_l = Produit.objects.create(nom="Commission", code_sku="SKU-L", prix_vente=Decimal("10"), taxgroup=group_l)

        migrate_tax_groups()
        migrate_tax_groups()

        self.assertEqual(active_codes(), EXPECTED_ACTIVE_CODES)
        for code in EXPECTED_ACTIVE_CODES + ("L", "N"):
            self.assertEqual(TaxGroup.objects.filter(code__iexact=code).count(), 1, code)
        lowercase_q.refresh_from_db()
        self.assertEqual((lowercase_q.code, lowercase_q.tax), ("Q", Decimal("8.00")))
        self.assertEqual(TaxGroup.objects.get(code="A").name, "GROUPE A (EXONERE)")
        self.assertEqual(TaxGroup.objects.get(code="B").tax, Decimal("16.00"))
        # Les groupes sans taux impose gardent leur regle actuelle.
        self.assertEqual(TaxGroup.objects.get(code="D").tax, Decimal("3.00"))
        group_l.refresh_from_db()
        group_n.refresh_from_db()
        self.assertTrue(group_l.is_active and group_n.is_active)
        produit_l.refresh_from_db()
        self.assertEqual(produit_l.taxgroup_id, group_l.pk)

    def test_reverse_restores_previous_list_without_deleting(self):
        group_l = TaxGroup.objects.get(code="L")
        group_l.is_active = False
        group_l.save(update_fields=["is_active"])

        tax_groups_migration.restore_previous_tax_groups(apps, None)

        self.assertEqual(TaxGroup.objects.get(code="A").name, "GROUPE A (EXONERE ET HORS CHAMP)")
        group_l.refresh_from_db()
        self.assertTrue(group_l.is_active)
        self.assertEqual(TaxGroup.objects.filter(code__in="QRS", is_active=False).count(), 3)


class HorsChampProductMigrationTests(TestCase):
    """Migration facturation 0059 : seul le code article « HORS CHAMP » passe de A a S."""

    def setUp(self):
        migrate_tax_groups()
        self.group_a = TaxGroup.objects.get(code="A")
        self.group_s = TaxGroup.objects.get(code="S")

    def test_only_products_coded_hors_champ_move_and_invoices_are_untouched(self):
        hors_champ = Produit.objects.create(nom="Vente de medicaments", code_sku="HORS CHAMP", prix_vente=Decimal("10"), taxgroup=self.group_a)
        exonere = Produit.objects.create(nom="Frais d'inscription", code_sku="SKU-A", prix_vente=Decimal("10"), taxgroup=self.group_a)
        user = get_user_model().objects.create_user(username="vendeur-s", email="vendeur-s@test.com", password="secret")
        commande = Commande.objects.create(
            point_de_vente=PointDeVente.objects.create(nom="PDV S"),
            vendeur=user,
            montant_total=Decimal("10.00"),
            montant_paye=Decimal("10.00"),
            tva_montant=Decimal("0.00"),
        )
        ligne = LigneCommande.objects.create(commande=commande, produit=hors_champ, quantite=Decimal("1"), prix_unitaire=Decimal("10"), remise=Decimal("0"))
        snapshot = LigneCommande.objects.get(pk=ligne.pk).groupe_taxation_snapshot

        hors_champ_migration.move_hors_champ_products_to_s(apps, None)

        hors_champ.refresh_from_db()
        exonere.refresh_from_db()
        self.assertEqual(hors_champ.taxgroup_id, self.group_s.pk)
        self.assertEqual(exonere.taxgroup_id, self.group_a.pk)
        self.assertEqual(LigneCommande.objects.get(pk=ligne.pk).groupe_taxation_snapshot, snapshot)

        hors_champ_migration.move_hors_champ_products_back_to_a(apps, None)
        hors_champ.refresh_from_db()
        self.assertEqual(hors_champ.taxgroup_id, self.group_a.pk)


class TaxGroupChoicesTests(TestCase):
    """Formulaires, imports et canaux n'utilisent que la liste active."""

    def setUp(self):
        migrate_tax_groups()
        self.group_l = TaxGroup.objects.get(code="L")
        self.group_n = TaxGroup.objects.get(code="N")
        self.group_t = TaxGroup.objects.create(code="T", name="RESERVE T", is_active=False)

    def test_product_form_offers_all_active_v2_groups(self):
        codes = set(ProduitForm().fields["taxgroup"].queryset.values_list("code", flat=True))

        self.assertEqual(codes, set(EXPECTED_ACTIVE_CODES))

    def test_product_still_classified_in_l_keeps_its_group_when_edited(self):
        produit = Produit.objects.create(nom="Retenue", code_sku="SKU-L", prix_vente=Decimal("10"), taxgroup=self.group_l)

        codes = set(ProduitForm(instance=produit).fields["taxgroup"].queryset.values_list("code", flat=True))

        self.assertIn("L", codes)
        self.assertIn("N", codes)

    def test_retired_group_cannot_be_reactivated(self):
        form = TaxGroupForm(
            data={"code": "T", "name": "x", "description": "", "tax": "0", "is_active": "on"},
            instance=self.group_t,
        )

        self.assertFalse(form.is_valid())
        self.assertIn("is_active", form.errors)

    def test_product_import_maps_hors_champ_to_s_and_eight_percent_to_q(self):
        cache = _build_tax_group_cache()

        self.assertEqual(cache["hors champ"].code, "S")
        self.assertEqual(cache["taxable 8%"].code, "Q")
        self.assertEqual(cache["r"].code, "R")
        self.assertEqual(cache["l"].code, "L")
        self.assertEqual(cache["n"].code, "N")

    def test_mcf_v2_accepts_a_to_s_and_refuses_reserved_groups_before_opening_invoice(self):
        """Protocole MCF-SFE v2 : groupes A a S applicables, T a Z reserves."""

        service = MCFInvoiceService(device=MCFDevice(name="MCF Test", port="COM9", company_nif="A1234567Q", company_isf="CD01004241-1"))

        service._ensure_tax_groups_supported(
            [{"tax_group": "B", "nom": "Biere"}, {"tax_group": "P", "nom": "Marche"}, {"tax_group": "q", "nom": "Ciment"}, {"tax_group": "S", "nom": "Hors champ"}]
        )
        with self.assertRaisesMessage(MCFUnsupportedTaxGroupError, "« Reserve » (groupe T)"):
            service._ensure_tax_groups_supported([{"tax_group": "B", "nom": "Biere"}, {"tax_group": "t", "nom": "Reserve"}])

    def test_audit_command_lists_group_a_and_products_on_retired_groups(self):
        Produit.objects.create(nom="Frais d'inscription", code_sku="SKU-A", prix_vente=Decimal("10"), taxgroup=TaxGroup.objects.get(code="A"))
        Produit.objects.create(nom="Reserve", code_sku="SKU-T", prix_vente=Decimal("10"), taxgroup=self.group_t)
        output = StringIO()

        call_command("audit_groupes_taxation", stdout=output)

        report = output.getvalue()
        self.assertIn("Produits du groupe A a verifier (exonere ou hors champ) : 1", report)
        self.assertIn("SKU-A - Frais d'inscription", report)
        self.assertIn("[T]", report)
        self.assertIn("SKU-T - Reserve", report)
