from django.contrib.auth import get_user_model
from rest_framework import serializers

from .models import BlogPost, Bug, Friendship, Message

User = get_user_model()


def _user_mini(user):
    if user is None:
        return None
    name = (f'{user.first_name} {user.last_name}'.strip()) or user.username
    return {'id': user.id, 'username': user.username, 'display_name': name}


# ── Message ───────────────────────────────────────────────────────────────────

class MessageListSerializer(serializers.ModelSerializer):
    sender_detail    = serializers.SerializerMethodField()
    recipient_detail = serializers.SerializerMethodField()

    def get_sender_detail(self, obj):    return _user_mini(obj.sender)
    def get_recipient_detail(self, obj): return _user_mini(obj.recipient)

    class Meta:
        model  = Message
        fields = ['id', 'sender_detail', 'recipient_detail', 'subject', 'sent_at', 'read_at']


class MessageDetailSerializer(serializers.ModelSerializer):
    sender_detail    = serializers.SerializerMethodField()
    recipient_detail = serializers.SerializerMethodField()

    def get_sender_detail(self, obj):    return _user_mini(obj.sender)
    def get_recipient_detail(self, obj): return _user_mini(obj.recipient)

    class Meta:
        model  = Message
        fields = ['id', 'sender_detail', 'recipient_detail', 'subject', 'body', 'sent_at', 'read_at']


class MessageCreateSerializer(serializers.ModelSerializer):
    recipient = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())

    class Meta:
        model  = Message
        fields = ['recipient', 'subject', 'body']

    def validate_recipient(self, value):
        if value == self.context['request'].user:
            raise serializers.ValidationError('You cannot send a message to yourself.')
        return value


# ── BlogPost ──────────────────────────────────────────────────────────────────

class BlogPostSerializer(serializers.ModelSerializer):
    author_detail = serializers.SerializerMethodField()

    def get_author_detail(self, obj): return _user_mini(obj.author)

    class Meta:
        model  = BlogPost
        fields = ['id', 'author_detail', 'title', 'body', 'is_public', 'created_at', 'updated_at']
        read_only_fields = ['created_at', 'updated_at']


# ── Bug ───────────────────────────────────────────────────────────────────────

class BugSerializer(serializers.ModelSerializer):
    reporter_detail = serializers.SerializerMethodField()

    def get_reporter_detail(self, obj): return _user_mini(obj.reporter)

    class Meta:
        model  = Bug
        fields = [
            'id', 'reporter_detail', 'title', 'description',
            'severity', 'status', 'created_at', 'updated_at', 'resolved_at',
        ]
        read_only_fields = ['status', 'resolved_at', 'created_at', 'updated_at']


# ── Friendship ────────────────────────────────────────────────────────────────

class FriendshipSerializer(serializers.ModelSerializer):
    from_user_detail = serializers.SerializerMethodField()
    to_user_detail   = serializers.SerializerMethodField()

    def get_from_user_detail(self, obj): return _user_mini(obj.from_user)
    def get_to_user_detail(self, obj):   return _user_mini(obj.to_user)

    class Meta:
        model  = Friendship
        fields = ['id', 'from_user_detail', 'to_user_detail', 'status', 'created_at']
        read_only_fields = ['status', 'created_at']


class FriendRequestSerializer(serializers.Serializer):
    to_user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())

    def validate_to_user(self, value):
        if value == self.context['request'].user:
            raise serializers.ValidationError('You cannot send a friend request to yourself.')
        return value
