from datetime import timedelta

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.utils import timezone

from .models import LoginEvent

# Verrouillage temporaire : 5 échecs en 15 minutes, par identifiant ou par adresse IP.
MAX_FAILURES = 5
LOCK_WINDOW = timedelta(minutes=15)
FAILURE_RESULTS = ("UNKNOWN", "BAD_PASSWORD", "INACTIVE", "LOCKED")


def is_locked(identifier: str, ip: str | None) -> bool:
    since = timezone.now() - LOCK_WINDOW
    scope = Q(username_attempted__iexact=identifier)
    if ip:
        scope |= Q(ip=ip)
    return LoginEvent.objects.filter(scope, result__in=FAILURE_RESULTS[:3], created_at__gte=since).count() >= MAX_FAILURES


class EmailOrMatriculeBackend(ModelBackend):
    """Authentifie par e-mail ou par matricule, avec verrouillage après échecs répétés."""

    def authenticate(self, request, username=None, password=None, **kwargs):
        User = get_user_model()
        identifier = (username or kwargs.get("email") or "").strip()
        if not identifier or password is None:
            return None
        ip = request.META.get("REMOTE_ADDR") if request else None
        ua = (request.META.get("HTTP_USER_AGENT", "") if request else "")[:255]
        if is_locked(identifier, ip):
            LoginEvent.objects.create(username_attempted=identifier, result="LOCKED", ip=ip, user_agent=ua)
            if request is not None:
                request.fm_login_locked = True
            return None
        user = User.objects.filter(email__iexact=identifier).first()
        if user is None:
            user = User.objects.filter(matricule__iexact=identifier).first()
        if user is None:
            LoginEvent.objects.create(username_attempted=identifier, result="UNKNOWN", ip=ip, user_agent=ua)
            return None
        if not user.is_active:
            LoginEvent.objects.create(user=user, username_attempted=identifier, result="INACTIVE", ip=ip, user_agent=ua)
            return None
        if user.check_password(password) and self.user_can_authenticate(user):
            LoginEvent.objects.create(user=user, username_attempted=identifier, result="SUCCESS", ip=ip, user_agent=ua)
            return user
        LoginEvent.objects.create(user=user, username_attempted=identifier, result="BAD_PASSWORD", ip=ip, user_agent=ua)
        return None
