from django.db.models import Sum
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from .models import QuotaDistribution, Quota


def recalculate_remaining_amount(quota):
    total_distributed = quota.distributions_assigned.aggregate(
        total=Sum('weight')
    )['total'] or 0

    quota.remaining_weight = quota.quota_weight - total_distributed
    quota.quota_distributed = total_distributed
    quota.save(update_fields=["remaining_weight", "quota_distributed"])


@receiver(post_save, sender=QuotaDistribution)
@receiver(post_delete, sender=QuotaDistribution)
def update_quota_remaining(sender, instance, **kwargs):
    recalculate_remaining_amount(instance.quota)
