from django.core.management.base import BaseCommand
from django.utils.text import slugify
from products.models import Product


class Command(BaseCommand):
    help = 'Generate slugs for existing products that do not have one'

    def handle(self, *args, **options):
        products = Product.objects.filter(slug='').select_related('vendor')
        total = products.count()
        self.stdout.write(f'Found {total} products without slugs')

        updated = 0
        for product in products:
            base_slug = f"{slugify(product.name)}-{slugify(product.vendor.shop_name)}"
            slug = base_slug
            counter = 1
            while Product.objects.filter(slug=slug).exclude(pk=product.pk).exists():
                slug = f"{base_slug}-{counter}"
                counter += 1
            product.slug = slug
            product.save(update_fields=['slug'])
            updated += 1

        self.stdout.write(self.style.SUCCESS(f'Successfully updated {updated} products with slugs'))
