from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from .models import Follow

@receiver(post_save, sender=Follow)
def update_follow_counts_on_follow(sender, instance, created, **kwargs):
    if created:
        follower = instance.follower
        following = instance.following

        follower.following_count = Follow.objects.filter(follower=follower).count()
        following.followers_count = Follow.objects.filter(following=following).count()

        follower.save()
        following.save()


@receiver(post_delete, sender=Follow)
def update_follow_counts_on_unfollow(sender, instance, **kwargs):
    follower = instance.follower
    following = instance.following

    follower.following_count = Follow.objects.filter(follower=follower).count()
    following.followers_count = Follow.objects.filter(following=following).count()

    follower.save()
    following.save()
