from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import IsAuthenticated
from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.pagination import CursorPagination
from django.contrib.auth import get_user_model
from ..serializers import ChatRoomSerializer, MessageChatSerializer
from ..models import ChatRoomModel as ChatRoom
from django.utils.timezone import now
UserGet = get_user_model()



class ChatRoomViewSet(ModelViewSet):
    serializer_class = ChatRoomSerializer
    permission_classes = [IsAuthenticated]
    queryset = ChatRoom.objects.all()

    def get_queryset(self):
        return self.queryset.filter(users=self.request.user).order_by('-updated_at')

    def perform_create(self, serializer):
        user_1 = self.request.user
        user_id = self.request.data.get("user_id")
        
        if not user_id:
            raise NotFound("user_id ارسال نشده است.")

        user_2 = UserGet.objects.filter(id=user_id).first()
        if not user_2:
            raise NotFound("کاربر مورد نظر یافت نشد.")

        existing_room = (
            ChatRoom.objects
            .filter(users=user_1)
            .filter(users=user_2)
        )

        if existing_room:
            self.instance = existing_room
            return

        chat_room = serializer.save()
        chat_room.users.add(user_1, user_2)
        chat_room.save()

        self.instance = chat_room



class MessageCursorPagination(CursorPagination):
    page_size = 30
    ordering = '-created_at'

class MessageViewSet(ModelViewSet):
    serializer_class = MessageChatSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = MessageCursorPagination


    def get_queryset(self):
        chat_room_id = self.request.query_params.get('chat_room')

        if not chat_room_id:
            return self.serializer_class.Meta.model.objects.none()

        return (
            self.serializer_class.Meta.model.objects
            .filter(chat_room_id=chat_room_id)
            .select_related("sender", "chat_room")
        )

    def perform_create(self, serializer):
        chat_room_id = self.request.data.get('chat_room')

        if not chat_room_id:
            raise ValidationError("فیلد chat_room اجباری است.")

        try:
            chat = ChatRoom.objects.get(id=chat_room_id)
        except ChatRoom.DoesNotExist:
            raise NotFound("چت‌روم پیدا نشد.")

        serializer.save(
            sender=self.request.user,
            chat_room=chat
        )

        chat.updated_at = now()
        chat.save(update_fields=['updated_at'])

