from django.db.models.signals import post_save
from django.dispatch import receiver

from core.apps.eggs.models.order import Order


@receiver(post_save, sender=Order)
def update_order_status(sender, instance, created, **kwargs):
    if created:
        if instance.courier_id is None:
            Order.objects.filter(id=instance.id).update(status="pending")
        elif instance.courier_id is not None and instance.status == "pending":
            Order.objects.filter(id=instance.id).update(status="delivery")
    else:
        if instance.courier_id is not None and instance.status == "pending":
            Order.objects.filter(id=instance.id).update(status="delivery")
        if instance.status == "success":
            order_items = instance.order_items.all()
            for item in order_items:
                if item.courier_product_id:
                    if item.courier_product_id.count < item.count:
                        print(item.courier_product_id.count, item.count)
                        raise ValueError(
                            "Count cannot be greater than courier product count"
                        )
                    item.courier_product_id.count -= item.count
                    print(item.courier_product_id.count, item.count)
                    item.courier_product_id.save()

        if (
            instance.price == instance.price_paid
            and instance.status == "success"
        ):
            Order.objects.filter(id=instance.id).update(status="done")
