"""
Role-scoped admin permissions (PRD §5: Moderator / Support admin / Finance
admin / Super admin have distinct restrictions — "Moderator cannot change
finance", "Finance admin — no content moderation unless separately
granted"). Applied only to the *mutating* admin-app endpoints in
views_admin.py — read/list endpoints stay on the plain `IsAdminUser` gate,
since broad read visibility across the admin panel (e.g. Support needing to
see a business's details while helping with a ticket) is normal and safe;
it's the ability to *act* that the PRD scopes per role. A `super` admin
always passes every check, including the ones below with an empty
`allowed_roles` set — those are the "no scoped role can do this, only
Super" endpoints (platform Settings, category/taxonomy management, Audit
Logs).
"""
from rest_framework.permissions import BasePermission


class IsScopedAdmin(BasePermission):
    allowed_roles = frozenset()

    def has_permission(self, request, view):
        user = request.user
        if not (user and user.is_authenticated and user.is_staff):
            return False
        return user.admin_role == 'super' or user.admin_role in self.allowed_roles


def admin_role_required(*roles):
    """Returns a permission class restricted to the given admin_role values (plus 'super', always allowed)."""
    return type('ScopedAdminPermission', (IsScopedAdmin,), {'allowed_roles': frozenset(roles)})


IsModerator = admin_role_required('moderator')
IsSupportAdmin = admin_role_required('support')
IsFinanceAdmin = admin_role_required('finance')
IsSuperAdminOnly = admin_role_required()  # empty set — only 'super' passes
