"""
ClearStaleSessionMiddleware

If a request comes in with a session cookie that Django cannot validate
(because the server was restarted, SECRET_KEY rotated, or session backend
cleared), silently delete the cookie and continue as anonymous.

This prevents infinite redirect loops on login-protected pages.
Industry standard: OWASP Session Management Cheat Sheet, §7.
"""
from django.conf import settings


class ClearStaleSessionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Detect stale session: cookie exists but Django can't load it
        session_cookie_name = getattr(settings, 'SESSION_COOKIE_NAME', 'sessionid')
        cookie_value = request.COOKIES.get(session_cookie_name)

        if cookie_value:
            # Check if Django successfully loaded a session
            session_key = getattr(request.session, 'session_key', None)
            is_empty = getattr(request.session, 'is_empty', lambda: True)()

            # If session appears empty, it's likely stale/corrupted
            if is_empty and not session_key:
                request._force_clear_stale_session = True

        response = self.get_response(request)

        # If we flagged it, delete the cookie from the response
        if getattr(request, '_force_clear_stale_session', False):
            response.delete_cookie(session_cookie_name)

        return response
