from __future__ import annotations

from django.conf import settings
from django.http import HttpResponseForbidden

from .utils import has_any_role, is_super_admin


class RoleContextMiddleware:
    """Attach role helpers and optional path guards to each request."""

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

    def __call__(self, request):
        request.user_role = request.user.role if request.user.is_authenticated else None
        request.is_super_admin = is_super_admin(request.user) if request.user.is_authenticated else False

        role_guard_map = getattr(settings, "ROLE_GUARD_MAP", {})
        if request.user.is_authenticated and role_guard_map:
            for path_prefix, allowed_roles in role_guard_map.items():
                if request.path.startswith(path_prefix) and not has_any_role(request.user, allowed_roles):
                    return HttpResponseForbidden("Insufficient role privileges for this path.")

        return self.get_response(request)
