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 OrganizationQuotaStats
from apps.warehouse.models import InventoryQuotaSaleItem


def warehouse_sold_and_balance(quota_stat: OrganizationQuotaStats):
    total_sold = quota_stat.sale_items.aggregate(
        total=Sum('weight')
    )['total'] or 0

    quota_stat.sold_amount = total_sold
    quota_stat.inventory_entry_balance = quota_stat.inventory_received - total_sold

    if quota_stat.inventory_entry_balance >= 0:
        # calculate extra sales & mines total extra sales weight from new inventory entry
        # and set the warehouse balance

        extra_sales = quota_stat.extra_sales.all()
        total_extra_sales_weight = extra_sales.aggregate(total=Sum('weight'))['total'] or 0
        if quota_stat.free_sale_balance != 0:
            if quota_stat.inventory_entry_balance >= quota_stat.free_sale_balance:
                quota_stat.inventory_entry_balance -= total_extra_sales_weight
                quota_stat.free_sale_balance = 0
            else:
                quota_stat.free_sale_balance -= quota_stat.inventory_entry_balance
                quota_stat.inventory_entry_balance = 0

        # calculate pre_sales & mines total pre_sales weight from new inventory entry
        # and set the warehouse balance

        pre_sales = quota_stat.pre_sales.all()
        total_pre_sales_weight = pre_sales.aggregate(total=Sum('weight'))['total'] or 0
        if total_pre_sales_weight != 0:
            if quota_stat.inventory_entry_balance >= quota_stat.pre_sale_balance:
                quota_stat.inventory_entry_balance -= total_pre_sales_weight
                quota_stat.pre_sale_balance = 0
            else:
                quota_stat.pre_sale_balance -= quota_stat.inventory_entry_balance
                quota_stat.inventory_entry_balance = 0

    quota_stat.save(update_fields=['sold_amount', 'inventory_entry_balance', 'free_sale_balance', 'pre_sale_balance'])


@receiver(post_save, sender=InventoryQuotaSaleItem)
@receiver(post_delete, sender=InventoryQuotaSaleItem)
def update_distribution_warehouse_sold_and_balance(sender, instance: InventoryQuotaSaleItem, **kwargs):
    # if object exists & pre sale is true
    if instance.quota_stat and not instance.quota_stat.quota.pre_sale:
        # if transaction status is success and warehouse management Done once, inventory_calculation set to true
        if instance.transaction.transaction_status == 'success' and instance.inventory_calculation is False:
            warehouse_sold_and_balance(
                quota_stat=instance.quota_stat,
            )
    else:
        print("quota distribution is null - warehouse app signals")
