from __future__ import annotations

from django.utils.deprecation import MiddlewareMixin
from django.contrib.auth.views import redirect_to_login


class WebAdminAuthRedirectMiddleware(MiddlewareMixin):
    """Redirect unauthenticated /webadmin/* requests to /webadmin/login/.

    This ensures that when a session expires (or user is anonymous), accessing
    any webadmin page leads to the webadmin login screen, regardless of the
    global LOGIN_URL setting.
    """

    def process_request(self, request):
        path = request.path
        if not path.startswith("/webadmin/"):
            return None
        if request.user.is_authenticated:
            return None
        # Allow the login and logout endpoints without redirect loop
        if path.startswith("/webadmin/login/") or path.startswith("/webadmin/logout/"):
            return None
        return redirect_to_login(request.get_full_path(), login_url="/webadmin/login/")

