from django.core.management.base import BaseCommand
from django.contrib.auth.models import User, Permission
from django.contrib.contenttypes.models import ContentType
from core.models import Vendor, Product, Category

class Command(BaseCommand):
    help = 'Create user accounts for existing vendors and grant permissions'

    def handle(self, *args, **kwargs):
        vendors = Vendor.objects.all()
        password = 'vendorpass'
        
        # Get permissions
        models = [Vendor, Product, Category]
        permissions = []
        for model in models:
            content_type = ContentType.objects.get_for_model(model)
            permissions.extend(Permission.objects.filter(content_type=content_type))
            
        for vendor in vendors:
            if not vendor.user:
                username = vendor.slug.replace('-', '_')
                
                # Ensure unique username
                base_username = username
                counter = 1
                while User.objects.filter(username=username).exists():
                    username = f"{base_username}{counter}"
                    counter += 1
                    
                user = User.objects.create_user(
                    username=username,
                    email='',
                    password=password,
                    is_staff=True
                )
                
                vendor.user = user
                vendor.save()
                self.stdout.write(self.style.SUCCESS(f'Created user "{username}" for vendor "{vendor.name}"'))
            else:
                user = vendor.user
                user.is_staff = True
                user.save()
            
            # Grant permissions
            user.user_permissions.add(*permissions)
            self.stdout.write(self.style.SUCCESS(f'Granted permissions to user "{user.username}"'))

        self.stdout.write(self.style.SUCCESS('Successfully processed vendor accounts. Default password: vendorpass'))