
from django.core.management.base import BaseCommand
from tenants.models import Tenant
import re

class Command(BaseCommand):
    help = 'Update existing tenant codes to be more user-friendly'

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be updated without making changes',
        )

    def handle(self, *args, **options):
        tenants = Tenant.objects.all()
        updated_count = 0
        
        for tenant in tenants:
            # Check if current code looks like random generated code (all caps + numbers)
            if re.match(r'^[A-Z0-9]{8}$', tenant.tenant_code):
                # Generate new user-friendly code
                old_code = tenant.tenant_code
                new_code = self.generate_friendly_code(tenant.name)
                
                if options['dry_run']:
                    self.stdout.write(f'Would update "{tenant.name}": {old_code} -> {new_code}')
                else:
                    # Ensure uniqueness
                    counter = 1
                    base_code = new_code
                    while Tenant.objects.filter(tenant_code=new_code).exclude(id=tenant.id).exists():
                        new_code = f"{base_code}{counter}"
                        counter += 1
                    
                    tenant.tenant_code = new_code
                    tenant.save()
                    updated_count += 1
                    self.stdout.write(
                        self.style.SUCCESS(f'Updated "{tenant.name}": {old_code} -> {new_code}')
                    )
        
        if options['dry_run']:
            self.stdout.write(f'Would update {updated_count} tenant codes')
        else:
            self.stdout.write(
                self.style.SUCCESS(f'Successfully updated {updated_count} tenant codes')
            )

    def generate_friendly_code(self, business_name):
        """Generate a friendly code from business name"""
        # Remove special characters and convert to lowercase
        code = re.sub(r'[^a-zA-Z0-9]', '', business_name.lower())
        
        # Limit to 10 characters
        code = code[:10]
        
        # If too short, add suffix
        if len(code) < 3:
            code = 'company'
            
        return code
