from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from django.db import transaction
from .models import QuestionConfiguration
from .serializers import QuestionConfigurationSerializer
from ErrorLogs.utils import log_error

# Create your views here.

class QuestionConfigurationViewSet(viewsets.ModelViewSet):
    queryset = QuestionConfiguration.objects.all()
    serializer_class = QuestionConfigurationSerializer
    permission_classes = [AllowAny]
    lookup_field = 'id'

    def list(self, request, *args, **kwargs):
        try:
            return super().list(request, *args, **kwargs)
        except Exception as e:
            log_error('QuestionConfigurationViewSet.list', e)
            return Response(
                {"error": "An error occurred while fetching question configurations"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def create(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                return super().create(request, *args, **kwargs)
        except Exception as e:
            log_error('QuestionConfigurationViewSet.create', e)
            return Response(
                {"error": "An error occurred while creating question configuration"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def retrieve(self, request, *args, **kwargs):
        try:
            return super().retrieve(request, *args, **kwargs)
        except Exception as e:
            log_error('QuestionConfigurationViewSet.retrieve', e)
            return Response(
                {"error": "An error occurred while fetching question configuration details"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def update(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                return super().update(request, *args, **kwargs)
        except Exception as e:
            log_error('QuestionConfigurationViewSet.update', e)
            return Response(
                {"error": "An error occurred while updating question configuration"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                return super().destroy(request, *args, **kwargs)
        except Exception as e:
            log_error('QuestionConfigurationViewSet.destroy', e)
            return Response(
                {"error": "An error occurred while deleting question configuration"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
