from rest_framework import serializers
from .models import FriendRequest, Friendship
from account.models import User


class UserMiniSerializer(serializers.ModelSerializer):
    profile_image = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ["id", "username", "profile_image", "neighborhood", "ward"]

    def get_profile_image(self, obj):
        request = self.context.get("request")
        if obj.profile_image and request:
            return request.build_absolute_uri(obj.profile_image.url)
        return None


class FriendRequestSerializer(serializers.ModelSerializer):
    sender   = UserMiniSerializer(read_only=True)
    receiver = UserMiniSerializer(read_only=True)

    class Meta:
        model = FriendRequest
        fields = ["id", "sender", "receiver", "status", "created_at"]


class FriendshipSerializer(serializers.ModelSerializer):
    friend = serializers.SerializerMethodField()

    class Meta:
        model = Friendship
        fields = ["id", "friend", "created_at"]

    def get_friend(self, obj):
        request = self.context.get("request")
        # Return the other user (not the requester)
        me = request.user if request else None
        other = obj.user2 if obj.user1 == me else obj.user1
        return UserMiniSerializer(other, context=self.context).data