from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from Auth.models import Profile
from N3wtSchool import bdd
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.exceptions import TokenError, InvalidToken
import logging

logger = logging.getLogger("Auth")


class EmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):

        if username is None:
            username = kwargs.get(Profile.USERNAME_FIELD)

        try:
            user = Profile.objects.get(email=username)

            # Vérifie le mot de passe de l'utilisateur
            if user.check_password(password):
                return user
        except Profile.DoesNotExist:
            return None


class LoggingJWTAuthentication(JWTAuthentication):
    """
    Surclasse JWTAuthentication pour loguer pourquoi un token Bearer est rejeté.
    Cela aide à diagnostiquer les 401 sans avoir à ajouter des prints partout.
    """

    def authenticate(self, request):
        header = self.get_header(request)
        if header is None:
            logger.debug("JWT: pas de header Authorization dans la requête %s %s",
                         request.method, request.path)
            return None

        raw_token = self.get_raw_token(header)
        if raw_token is None:
            logger.debug("JWT: header Authorization présent mais token vide pour %s %s",
                         request.method, request.path)
            return None

        try:
            validated_token = self.get_validated_token(raw_token)
        except InvalidToken as e:
            logger.warning(
                "JWT: token invalide pour %s %s — %s",
                request.method, request.path, str(e)
            )
            raise

        try:
            user = self.get_user(validated_token)
        except Exception as e:
            logger.warning(
                "JWT: utilisateur introuvable pour %s %s — %s",
                request.method, request.path, str(e)
            )
            raise

        logger.debug("JWT: authentification réussie user_id=%s pour %s %s",
                     user.pk, request.method, request.path)
        return user, validated_token

