
from django.core.management.base import BaseCommand
from django.utils.text import slugify
from tenants.models import Tenant

class Command(BaseCommand):
    help = 'Update tenant slugs for existing tenants'

    def handle(self, *args, **options):
        tenants = Tenant.objects.all()
        
        for tenant in tenants:
            if not tenant.slug:
                # Generate slug from name
                slug = slugify(tenant.name)
                counter = 1
                original_slug = slug
                
                # Ensure uniqueness
                while Tenant.objects.filter(slug=slug).exclude(id=tenant.id).exists():
                    slug = f"{original_slug}-{counter}"
                    counter += 1
                
                tenant.slug = slug
                tenant.save()
                
                self.stdout.write(
                    self.style.SUCCESS(f'Updated tenant "{tenant.name}" with slug: {slug}')
                )
            else:
                self.stdout.write(f'Tenant "{tenant.name}" already has slug: {tenant.slug}')
        
        self.stdout.write(
            self.style.SUCCESS('Successfully updated all tenant slugs')
        )
