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

User = get_user_model()


class FollowSerializer(serializers.Serializer):
    user_id    = serializers.IntegerField()
    username   = serializers.CharField()
    is_following = serializers.BooleanField(default=False)


class UserFollowSerializer(serializers.ModelSerializer):
    profile_image   = serializers.SerializerMethodField()
    followers_count = serializers.SerializerMethodField()
    following_count = serializers.SerializerMethodField()

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

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

    def get_followers_count(self, obj):
        # Use live DB count — always accurate
        from .models import Follow
        return Follow.objects.filter(following=obj).count()

    def get_following_count(self, obj):
        from .models import Follow
        return Follow.objects.filter(follower=obj).count()