from rest_framework import viewsets, status
from rest_framework.response import Response
from chat.services.message_service import message_service
from chat.serializers.message_serializers import MessageSerializer, MessageCreateSerializer
from rest_framework.permissions import IsAuthenticated
from drf_spectacular.utils import extend_schema, extend_schema_view

@extend_schema_view(
    list=extend_schema(tags=['2. Application Service']),
    create=extend_schema(tags=['2. Application Service']),
)
class MessageViewSet(viewsets.GenericViewSet):
    """View สำหรับจัดการข้อความที่อยู่ภายใต้ Ticket"""
    permission_classes = [IsAuthenticated]

    def list(self, request):
        ticket_id = request.query_params.get('ticket_id')
        messages = message_service.get_ticket_messages(ticket_id=ticket_id)
        serializer = MessageSerializer(messages, many=True)
        return Response(serializer.data)

    def create(self, request):
        serializer = MessageCreateSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        new_message = message_service.create_and_send_message(
            ticket_id=serializer.validated_data['ticket'].id,
            sender=request.user,
            content=serializer.validated_data['content'],
            message_type=serializer.validated_data['message_type']
        )
        response_serializer = MessageSerializer(new_message)
        return Response(response_serializer.data, status=status.HTTP_201_CREATED)

