from rest_framework import generics, permissions, status
from rest_framework.views import APIView
from rest_framework.response import Response

from tickets.models import Ticket
from tickets.api.serializers import TicketDetailSerializer, TicketSerializer, TicketStatusSerializer
from tickets.api.permissions import UserTicketAccessPermission, UserTicketStatusAccessPermission


class TicketDetailAPIView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Ticket.objects.all()
    serializer_class = TicketDetailSerializer
    permission_classes = [permissions.IsAuthenticated & UserTicketAccessPermission]

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.archive()
        return Response(status=status.HTTP_204_NO_CONTENT)


class TicketCreateAPIView(generics.CreateAPIView):
    queryset = Ticket.objects.all()
    serializer_class = TicketSerializer
    permission_classes = [permissions.IsAuthenticated & UserTicketAccessPermission]

    def perform_create(self, serializer):
        if serializer.is_valid():
            serializer.save(created_by=self.request.user) 


class TicketStatusAPIView(generics.RetrieveUpdateAPIView):
    queryset = Ticket.objects.all()
    serializer_class = TicketStatusSerializer
    permission_classes = [permissions.IsAuthenticated & UserTicketStatusAccessPermission]