from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework_simplejwt.authentication import JWTAuthentication

from module_project import constants
from module_project.utils import ApiResponse

from ..models import ContactUs, Feedback
from .serializers import ContactUsSerializer, FeedbackSerializer


class ContactusAPIView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]
    serializer_class = ContactUsSerializer
    model = ContactUs

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        if not serializer.is_valid():
            return ApiResponse.error(message=constants.FAILURE, errors=serializer.errors)
        try:
            serializer.save()
        except Exception as e:
            return ApiResponse.error(message=constants.FAILURE, errors=str(e))
        return ApiResponse.success(message=constants.SUCCESS, data=serializer.data)


class FeedbackAPIView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]
    serializer_class = FeedbackSerializer
    model = Feedback

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        if not serializer.is_valid():
            return ApiResponse.error(message=constants.FAILURE, errors=serializer.errors)
        try:
            serializer.save(principal=request.user)
        except Exception as e:
            return ApiResponse.error(message=constants.FAILURE, errors=str(e))
        return ApiResponse.success(message=constants.SUCCESS, data=serializer.data)
