# middleware.py

from django.utils.timezone import now
from .models import User  # Import your User model

import threading

from django.utils.deprecation import MiddlewareMixin

_thread_locals = threading.local()


class TemporaryVerificationMiddleware:
    """
    Middleware that checks the user's temporary verification expiration date.
    If the expiration date is greater than or equal to the current date,
    the user's verification status is set to None (unverified).
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Get the current date
        current_date = now().date()

        # Get all users whose temporary verification expiration date is greater than or equal to today's date
        users = User.objects.filter(temporary_verification_expiration__lte=current_date)

        # Loop through each user and unverify them
        for user in users:
            user.verified = False  # Unverify the user
            user.save()

        # Continue processing the request
        response = self.get_response(request)
        return response
    

def get_current_user():
    return getattr(_thread_locals, 'user', None)


def get_current_request():
    return getattr(_thread_locals, "request", None)

class CurrentUserMiddleware(MiddlewareMixin):
    """
    Middleware to store the current user in thread-local storage.
    """
    def process_request(self, request):
        _thread_locals.request = request
        _thread_locals.user = request.user if request.user.is_authenticated else None
