from rest_framework import serializers
from .models import Message
from community.models import Room


class ReplyPreviewSerializer(serializers.ModelSerializer):
    sender_username = serializers.SerializerMethodField()

    class Meta:
        model = Message
        fields = ["id", "content", "sender_username"]

    def get_sender_username(self, obj):
        return obj.sender.username if obj.sender else "Unknown"


class MessageSerializer(serializers.ModelSerializer):
    sender = serializers.SerializerMethodField()
    reply_to = ReplyPreviewSerializer(read_only=True)

    class Meta:
        model = Message
        fields = [
            "id", "content", "message_type", "image",
            "sender", "reply_to", "reactions",
            "created_at", "is_deleted",
        ]

    def get_sender(self, obj):
        if not obj.sender:
            return None
        request = self.context.get("request")
        avatar = None
        if obj.sender.profile_image:
            if request:
                avatar = request.build_absolute_uri(obj.sender.profile_image.url)
            else:
                avatar = obj.sender.profile_image.url
        return {
            "id": obj.sender.id,
            "username": obj.sender.username,
            "profile_image": avatar,
            "neighborhood": obj.sender.neighborhood or "",
        }


class RoomSerializer(serializers.ModelSerializer):
    is_member = serializers.SerializerMethodField()
    last_message = serializers.SerializerMethodField()

    class Meta:
        model = Room
        fields = [
            "id", "name", "slug", "description",
            "room_type", "icon", "member_count",
            "is_member", "last_message", "created_at",
        ]

    def get_is_member(self, obj):
        request = self.context.get("request")
        if not request or not request.user.is_authenticated:
            return False
        return obj.members.filter(id=request.user.id).exists()

    def get_last_message(self, obj):
        msg = obj.messages.filter(is_deleted=False).order_by("-created_at").first()
        if not msg:
            return None
        return {
            "content": msg.content[:60],
            "sender": msg.sender.username if msg.sender else "",
            "created_at": msg.created_at.isoformat(),
        }