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

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

from facturation.models import PointDeVente, UserPermissionBouton

from .forms import (
    UserAdminChangeForm as BaseUserAdminChangeForm,
    UserAdminCreationForm as BaseUserAdminCreationForm,
    UserManagementCreateForm as BaseUserManagementCreateForm,
    UserManagementUpdateForm as BaseUserManagementUpdateForm,
)
from .views import (
    UserListView as BaseUserListView,
    UserManagementCreateView as BaseUserManagementCreateView,
    UserManagementUpdateView as BaseUserManagementUpdateView,
)


class AccountsRoutingTests(SimpleTestCase):
    """Regroupe les tests de stabilite des routes publiques des utilisateurs."""

    def test_facturation_user_routes_keep_public_paths(self):
        """Verifie que les routes publiques des utilisateurs restent stables."""

        self.assertEqual(reverse("facturation:user-list"), "/utilisateurs/")
        self.assertEqual(reverse("facturation:user-create"), "/utilisateurs/creer/")
        self.assertEqual(reverse("facturation:user-update", args=[1]), "/utilisateurs/1/modifier/")


class AccountsCompatibilityTests(SimpleTestCase):
    """Regroupe les tests de compatibilite des imports historiques."""

    def test_facturation_reexports_user_forms_and_views(self):
        """Verifie que facturation reexporte toujours les composants comptes."""

        from facturation.forms import (
            UserAdminChangeForm as FacturationUserAdminChangeForm,
            UserAdminCreationForm as FacturationUserAdminCreationForm,
            UserManagementCreateForm as FacturationUserManagementCreateForm,
            UserManagementUpdateForm as FacturationUserManagementUpdateForm,
        )
        from facturation.views import (
            UserListView as FacturationUserListView,
            UserManagementCreateView as FacturationUserManagementCreateView,
            UserManagementUpdateView as FacturationUserManagementUpdateView,
        )

        self.assertIs(FacturationUserAdminCreationForm, BaseUserAdminCreationForm)
        self.assertIs(FacturationUserAdminChangeForm, BaseUserAdminChangeForm)
        self.assertIs(FacturationUserManagementCreateForm, BaseUserManagementCreateForm)
        self.assertIs(FacturationUserManagementUpdateForm, BaseUserManagementUpdateForm)
        self.assertIs(FacturationUserListView, BaseUserListView)
        self.assertIs(FacturationUserManagementCreateView, BaseUserManagementCreateView)
        self.assertIs(FacturationUserManagementUpdateView, BaseUserManagementUpdateView)


class AccountsEndpointsTests(TestCase):
    """Regroupe les tests lies aux ecrans de gestion des comptes."""

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

        self.point_de_vente = PointDeVente.objects.create(nom="PDV Accounts")
        self.second_point_de_vente = PointDeVente.objects.create(nom="PDV Accounts B")
        self.super_admin = get_user_model().objects.create_superuser(
            username="super-accounts",
            email="super-accounts@test.com",
            password="secret123",
            role="ADMIN",
            point_de_vente=self.point_de_vente,
        )
        self.admin_user = get_user_model().objects.create_user(
            username="admin-accounts",
            email="admin-accounts@test.com",
            password="secret123",
            role="ADMIN",
            is_staff=True,
            point_de_vente=self.point_de_vente,
            created_by=self.super_admin,
        )
        self.owned_user = get_user_model().objects.create_user(
            username="vendeur-accounts",
            email="vendeur-accounts@test.com",
            password="secret123",
            role="VENDEUR",
            point_de_vente=self.point_de_vente,
            created_by=self.admin_user,
        )
        self.client.force_login(self.admin_user)

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

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

    def test_user_pages_still_render_with_compatibility_templates(self):
        """Verifie que les ecrans utilisateurs restent accessibles et rendus."""

        list_response = self.client.get(reverse("facturation:user-list"))
        create_response = self.client.get(reverse("facturation:user-create"))
        update_response = self.client.get(reverse("facturation:user-update", args=[self.owned_user.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, "facturation/user_list.html")
        self.assertTemplateUsed(list_response, "accounts/user_list.html")
        self.assertTemplateUsed(create_response, "facturation/user_form.html")
        self.assertTemplateUsed(create_response, "accounts/user_form.html")
        self.assertTemplateUsed(update_response, "facturation/user_form.html")
        self.assertTemplateUsed(update_response, "accounts/user_form.html")
        self.assertContains(update_response, "Point de vente / Magasin")
        self.assertContains(update_response, "Tous les points de vente")
        self.assertContains(update_response, "Boutons, exports")

    def test_user_create_keeps_created_by_behavior(self):
        """Verifie que la creation continue de rattacher le compte a son createur."""

        response = self.client.post(
            reverse("facturation:user-create"),
            {
                "username": "vendeur-nouveau-accounts",
                "first_name": "Vendeur",
                "last_name": "Nouveau",
                "email": "vendeur-nouveau-accounts@test.com",
                "role": "VENDEUR",
                "points_de_vente": [self.point_de_vente.pk, self.second_point_de_vente.pk],
                "is_active": "on",
                "password1": "secret123456",
                "password2": "secret123456",
            },
            follow=True,
        )

        self.assertEqual(response.status_code, 200)
        created_user = get_user_model().objects.get(username="vendeur-nouveau-accounts")
        self.assertEqual(created_user.created_by, self.admin_user)
        self.assertEqual(created_user.point_de_vente, self.point_de_vente)
        self.assertQuerySetEqual(
            created_user.points_de_vente.order_by("pk"),
            [self.point_de_vente, self.second_point_de_vente],
            transform=lambda point: point,
        )
        messages_text = " ".join(self._message_texts(response))
        self.assertIn("vendeur-nouveau-accounts", messages_text)
        self.assertIn("cr", messages_text)

    def test_user_update_displays_success_message(self):
        """Verifie le message de succes apres modification d’un utilisateur."""

        response = self.client.post(
            reverse("facturation:user-update", args=[self.owned_user.pk]),
            {
                "username": self.owned_user.username,
                "first_name": "Prenom modifie",
                "last_name": "Nom modifie",
                "email": self.owned_user.email,
                "role": "VENDEUR",
                "points_de_vente": [self.second_point_de_vente.pk],
                "is_active": "on",
                "new_password": "",
            },
            follow=True,
        )

        self.assertEqual(response.status_code, 200)
        self.owned_user.refresh_from_db()
        self.assertEqual(self.owned_user.first_name, "Prenom modifie")
        self.assertEqual(self.owned_user.point_de_vente, self.second_point_de_vente)
        self.assertQuerySetEqual(
            self.owned_user.points_de_vente.order_by("pk"),
            [self.second_point_de_vente],
            transform=lambda point: point,
        )
        messages_text = " ".join(self._message_texts(response))
        self.assertIn("modifi", messages_text)

    def test_user_update_all_points_option_assigns_accessible_points(self):
        """Verifie que l'option Tous les points affecte tous les magasins accessibles."""

        response = self.client.post(
            reverse("facturation:user-update", args=[self.owned_user.pk]),
            {
                "username": self.owned_user.username,
                "first_name": self.owned_user.first_name,
                "last_name": self.owned_user.last_name,
                "email": self.owned_user.email,
                "role": "VENDEUR",
                "points_de_vente": ["all"],
                "is_active": "on",
                "new_password": "",
                "new_password2": "",
            },
            follow=True,
        )

        self.assertEqual(response.status_code, 200)
        self.owned_user.refresh_from_db()
        self.assertQuerySetEqual(
            self.owned_user.points_de_vente.order_by("pk"),
            [self.point_de_vente, self.second_point_de_vente],
            transform=lambda point: point,
        )

    def test_user_update_saves_ui_permissions(self):
        """Verifie que l'ecran utilisateur sauvegarde aussi les boutons et exports UI."""

        self.client.force_login(self.super_admin)

        response = self.client.post(
            reverse("facturation:user-update", args=[self.owned_user.pk]),
            {
                "username": self.owned_user.username,
                "first_name": self.owned_user.first_name,
                "last_name": self.owned_user.last_name,
                "email": self.owned_user.email,
                "role": "VENDEUR",
                "points_de_vente": [self.point_de_vente.pk],
                "is_active": "on",
                "new_password": "",
                "new_password2": "",
                "ui_permissions_present": "1",
                "ui_permission__user__produits__show_export_button": "on",
            },
            follow=True,
        )

        self.assertEqual(response.status_code, 200)
        self.assertTrue(
            UserPermissionBouton.objects.get(
                user=self.owned_user,
                module="produits",
                bouton="show_export_button",
            ).autorise
        )
