from rest_framework import permissions

class IsAdminRole(permissions.BasePermission):
    """
    Permite acceso a ADMINISTRADOR/superusers, y a CONTADOR de forma de solo lectura o para cambiar_estado.
    """
    def has_permission(self, request, view):
        if not request.user or not request.user.is_authenticated:
            return False
            
        if getattr(request.user, 'is_superuser', False):
            return True
            
        if hasattr(request.user, 'perfil'):
            rol = request.user.perfil.rol
            if rol == 'CONTADOR':
                if request.method in permissions.SAFE_METHODS:
                    return True
                if request.method == 'PATCH' and getattr(view, 'action', None) == 'cambiar_estado':
                    return True
                return False
            return rol == 'ADMINISTRADOR'
            
        return False
