from rest_framework import viewsets
from rest_framework.response import Response
from api import models, serializers
from django.db.models import Max

class RolViewSet(viewsets.ModelViewSet):
    queryset = models.Rol.objects.all()
    serializer_class = serializers.RolSerializer

    def create(self, request, *args, **kwargs):
        # se indica que si no se indico el id, entonces sea el maximo + 1
        if not request.data.get('id_rol', None):
            max_id = models.Rol.objects.aggregate(Max('id_rol'))['id_rol__max']
            new_id = max_id + 1 if max_id is not None else 1
            request.data['id_rol'] = new_id
        
        return super().create(request, *args, **kwargs)
    
    def destroy(self, request, pk=None):
        try:
            return super().destroy(request, pk)
        except Exception as ex:
            return Response(str(ex), status=400)