from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from django.shortcuts import get_object_or_404
from community.models import Room, RoomMembership
from .models import Message
from .serializers import MessageSerializer, RoomSerializer


class RoomListView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        rooms = Room.objects.filter(is_active=True).order_by("room_type", "name")
        serializer = RoomSerializer(rooms, many=True, context={"request": request})
        return Response(serializer.data)


class RoomDetailView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, slug):
        room = get_object_or_404(Room, slug=slug, is_active=True)

        # Auto-join if not a member
        membership, created = RoomMembership.objects.get_or_create(
            user=request.user, room=room,
            defaults={"role": "member"}
        )
        if created:
            room.member_count = room.members.count()
            room.save(update_fields=["member_count"])

        serializer = RoomSerializer(room, context={"request": request})
        return Response(serializer.data)


class MessageHistoryView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, slug):
        room = get_object_or_404(Room, slug=slug)
        messages = (
            Message.objects
            .filter(room=room, is_deleted=False)
            .select_related("sender", "reply_to__sender")
            .order_by("-created_at")[:50]
        )
        messages = list(reversed(messages))
        serializer = MessageSerializer(messages, many=True, context={"request": request})
        return Response(serializer.data)


class ReportMessageView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, message_id):
        from .models import MessageReport
        message = get_object_or_404(Message, id=message_id)
        reason = request.data.get("reason", "other")
        details = request.data.get("details", "")

        report, created = MessageReport.objects.get_or_create(
            message=message,
            reported_by=request.user,
            defaults={"reason": reason, "details": details}
        )
        if not created:
            return Response({"detail": "Already reported."}, status=status.HTTP_400_BAD_REQUEST)

        message.is_reported = True
        message.save(update_fields=["is_reported"])

        return Response({"detail": "Message reported. Thank you."})