"""
Tests unitaires pour le module Establishment.
Vérifie que les endpoints requièrent une authentification JWT.
"""

from django.test import TestCase, override_settings
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from rest_framework_simplejwt.tokens import RefreshToken

from Auth.models import Profile


def create_user(email="establishment_test@example.com", password="testpassword123"):
    return Profile.objects.create_user(username=email, email=email, password=password)


def get_jwt_token(user):
    refresh = RefreshToken.for_user(user)
    return str(refresh.access_token)


TEST_REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

TEST_CACHES = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}


@override_settings(
    CACHES=TEST_CACHES,
    SESSION_ENGINE='django.contrib.sessions.backends.db',
    REST_FRAMEWORK=TEST_REST_FRAMEWORK,
)
class EstablishmentEndpointAuthTest(TestCase):
    """Tests d'authentification sur les endpoints Establishment."""

    def setUp(self):
        self.client = APIClient()
        self.list_url = reverse("Establishment:establishment_list_create")
        self.user = create_user()

    def test_get_establishments_sans_auth_retourne_401(self):
        """GET /Establishment/establishments sans token doit retourner 401."""
        response = self.client.get(self.list_url)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_post_establishment_sans_auth_retourne_401(self):
        """POST /Establishment/establishments sans token doit retourner 401."""
        import json
        response = self.client.post(
            self.list_url,
            data=json.dumps({"name": "Ecole Alpha"}),
            content_type="application/json",
        )
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_get_establishment_detail_sans_auth_retourne_401(self):
        """GET /Establishment/establishments/{id} sans token doit retourner 401."""
        url = reverse("Establishment:establishment_detail", kwargs={"id": 1})
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_put_establishment_sans_auth_retourne_401(self):
        """PUT /Establishment/establishments/{id} sans token doit retourner 401."""
        import json
        url = reverse("Establishment:establishment_detail", kwargs={"id": 1})
        response = self.client.put(
            url,
            data=json.dumps({"name": "Ecole Beta"}),
            content_type="application/json",
        )
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_delete_establishment_sans_auth_retourne_401(self):
        """DELETE /Establishment/establishments/{id} sans token doit retourner 401."""
        url = reverse("Establishment:establishment_detail", kwargs={"id": 1})
        response = self.client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_get_establishments_avec_auth_retourne_200(self):
        """GET /Establishment/establishments avec token valide doit retourner 200."""
        token = get_jwt_token(self.user)
        self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
        response = self.client.get(self.list_url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
