from django.db.models import Sum
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from apps.product.models import QuotaDistribution
from .models import InventoryEntry, InventoryQuotaSaleTransaction


def calculate_warehouse_entry(quota_distribution):
    total_entry = quota_distribution.inventory_entry.aggregate(
        total=Sum('weight')
    )['total'] or 0

    quota_distribution.warehouse_entry = total_entry
    quota_distribution.save(update_fields=['warehouse_entry'])


def warehouse_sold_and_balance(quota_distribution):
    total_sold = quota_distribution.inventory_sales.aggregate(
        total=Sum('weight')
    )['total'] or 0

    quota_distribution.been_sold = total_sold
    quota_distribution.warehouse_balance = quota_distribution.warehouse_entry - total_sold
    quota_distribution.save(update_fields=['been_sold', 'warehouse_balance'])


@receiver(post_save, sender=InventoryEntry)
@receiver(post_delete, sender=InventoryEntry)
def update_distribution_warehouse_entry(sender, instance, **kwargs):
    calculate_warehouse_entry(instance.distribution)
    warehouse_sold_and_balance(instance.distribution)


@receiver(post_save, sender=InventoryQuotaSaleTransaction)
@receiver(post_delete, sender=InventoryQuotaSaleTransaction)
def update_distribution_warehouse_sold_and_balance(sender, instance, **kwargs):
    warehouse_sold_and_balance(instance.quota_distribution)
