from django.core.management.base import BaseCommand
from project.models import BouquetVariant
from project.utils.woocommerce_service import update_variant_stock


class Command(BaseCommand):
    help = "Push local stem availability back to WooCommerce for all bouquet variants"

    def handle(self, *args, **options):
        success_count = 0
        errors = []

        for variant in BouquetVariant.objects.all().select_related("bouquet"):
            try:
                stems = variant.stems.all()

                if not stems.exists():
                    # No stem mapping, skip gracefully
                    self.stdout.write(
                        self.style.WARNING(f"⚠️ Skipping {variant} (no stems linked)")
                    )
                    continue

                # Calculate max bouquets possible = min(stock // units_needed)
                max_bouquets = min(
                    vstem.stem.available_quantity() // vstem.units_needed
                    for vstem in stems
                )

                # Ensure stock never goes below 0
                max_bouquets = max(0, max_bouquets)

                # Send update to Woo
                ok = update_variant_stock(
                    variant.woo_variation_id,
                    in_stock=(max_bouquets > 0),
                    quantity=max_bouquets,
                )

                if ok:
                    self.stdout.write(
                        self.style.SUCCESS(
                            f"✅ Synced {variant.bouquet.name} - {variant.size} "
                            f"(stock={max_bouquets})"
                        )
                    )
                    success_count += 1
                else:
                    errors.append(
                        f"Variant {variant.woo_variation_id} update failed"
                    )

            except Exception as e:
                errors.append(f"Variant {getattr(variant, 'woo_variation_id', '?')} error: {e}")

        self.stdout.write(self.style.SUCCESS(f"\n✅ {success_count} variants synced"))
        if errors:
            self.stdout.write(self.style.WARNING(f"\n⚠️ {len(errors)} errors:"))
            for err in errors:
                self.stdout.write(f"  - {err}")
