from django.shortcuts import redirect
from django.urls import reverse

class ValidacionPinMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.user.is_authenticated:
            # Si el usuario tiene el PIN temporal, lo atrapamos
            if getattr(request.user, 'requiere_cambio_pin', False):
                
                # Le permitimos ir SOLO a cambiar el PIN, a desloguearse, o al panel de admin
                rutas_permitidas = [reverse('cambiar_pin'), reverse('account_logout')]
                
                if request.path not in rutas_permitidas and not request.path.startswith('/admin/'):
                    return redirect('cambiar_pin')
                    
        return self.get_response(request)