from rest_framework import serializers
from .models import Discussion, Message, MessageAttachment, MessageReaction


class MessageReactionSerializer(serializers.ModelSerializer):
    user_name = serializers.CharField(source='user.full_name', read_only=True)

    class Meta:
        model = MessageReaction
        fields = ['id', 'user', 'user_name', 'emoji']
        read_only_fields = ['id', 'user']


class MessageAttachmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = MessageAttachment
        fields = ['id', 'file', 'file_name', 'uploaded_at']


class MessageSerializer(serializers.ModelSerializer):
    author_name = serializers.CharField(source='author.full_name', read_only=True)
    author_initials = serializers.CharField(source='author.initials', read_only=True)
    author_role = serializers.SerializerMethodField()

    def get_author_role(self, obj):
        return obj.author.roles.first().name if obj.author.roles.exists() else 'Member'
    reactions = MessageReactionSerializer(many=True, read_only=True)
    attachments = MessageAttachmentSerializer(many=True, read_only=True)
    reply_count = serializers.SerializerMethodField()

    class Meta:
        model = Message
        fields = [
            'id', 'discussion', 'author', 'author_name', 'author_initials',
            'author_role', 'content', 'parent', 'is_pinned', 'is_deleted',
            'reactions', 'attachments', 'reply_count',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'author', 'created_at', 'updated_at']

    def get_reply_count(self, obj):
        return obj.replies.filter(is_deleted=False).count()


class DiscussionSerializer(serializers.ModelSerializer):
    title = serializers.SerializerMethodField()
    description = serializers.SerializerMethodField()
    last_message = serializers.SerializerMethodField()
    message_count = serializers.SerializerMethodField()

    class Meta:
        model = Discussion
        fields = ['id', 'lead', 'project', 'task', 'board_type', 'title', 'description', 'last_message', 'message_count', 'created_at']
        read_only_fields = ['id', 'created_at']

    def get_title(self, obj):
        if obj.lead:
            return obj.lead.title
        if obj.project:
            return obj.project.name
        if obj.task:
            return obj.task.title
        return f"Board #{obj.id}"

    def get_description(self, obj):
        """Return the contextual description for the linked entity."""
        if obj.task and obj.task.description:
            return obj.task.description[:200]
        if obj.lead and obj.lead.requirements:
            return obj.lead.requirements[:200]
        if obj.project:
            return f"{obj.project.client_name} — {obj.project.get_stage_display()}"
        return ''

    def get_last_message(self, obj):
        last = obj.messages.filter(is_deleted=False).order_by('-created_at').first()
        if last:
            return {
                'content': last.content,
                'author_name': last.author.full_name if last.author else 'Unknown',
                'created_at': last.created_at
            }
        return None

    def get_message_count(self, obj):
        return obj.messages.filter(is_deleted=False).count()
