from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from project.models import Stem, BouquetVariant
from project.utils.woocommerce_service import update_variant_stock

@receiver(post_save, sender=Stem)
def sync_stem_stock_to_woo(sender, instance, **kwargs):
    """
    Whenever a Stem stock is updated in Django admin,
    check all BouquetVariants that use this stem
    and sync their stock status to WooCommerce.
    """
    variants = BouquetVariant.objects.filter(stems__stem=instance).distinct()
    for variant in variants:
        can_make = True
        for vstem in variant.stems.all():
            if vstem.stem.available_quantity() < vstem.units_needed:
                can_make = False
                break

        update_variant_stock(
            variant.woo_variation_id,
            in_stock=can_make,
            quantity=None  # optional: push actual stock qty
        )
        
        
@receiver([post_save, post_delete], sender=Stem)
def auto_sync_stock(sender, instance, **kwargs):
    for vstem in instance.bouquetvariantstem_set.all():
        variant = vstem.variant
        can_make = all(
            s.stem.available_quantity() >= s.units_needed
            for s in variant.stems.all()
        )
        update_variant_stock(variant.woo_variation_id, in_stock=can_make, quantity=None)
