from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from .models import AuditLog
from .serializers import AuditLogSerializer


class AuditLogViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = AuditLog.objects.select_related('user').all()
    serializer_class = AuditLogSerializer
    filterset_fields = ['action', 'model_name', 'user']
    search_fields = ['object_repr', 'model_name']
    ordering_fields = ['created_at']

    def get_queryset(self):
        # AuditLog has no client FK — it reaches the client through the acting
        # user. Non-internal users only ever see their own client's activity.
        from core.scoping import scope_to_client
        return scope_to_client(super().get_queryset(), self.request.user,
                               lookup='user__client_id')
