
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.db import transaction

User = get_user_model()

class Command(BaseCommand):
    help = 'Check existing superuser accounts and create one if needed'

    def add_arguments(self, parser):
        parser.add_argument('--create', action='store_true', help='Create a new superuser if none exists')
        parser.add_argument('--username', type=str, help='Username for the new superuser')
        parser.add_argument('--email', type=str, help='Email for the new superuser')

    def handle(self, *args, **options):
        # List existing superusers
        superusers = User.objects.filter(is_superuser=True)
        
        self.stdout.write(f"Found {superusers.count()} superuser(s):")
        for user in superusers:
            status = "Active" if user.is_active else "Inactive"
            self.stdout.write(f"  - {user.username} ({user.email}) - {status}")
            
            # Check if password is usable
            if not user.has_usable_password():
                self.stdout.write(f"    WARNING: {user.username} has no usable password!")
        
        # Create superuser if requested and none exists
        if options['create']:
            if not superusers.exists():
                username = options['username'] or 'director'
                email = options['email'] or 'director@optinet.co.ke'
                
                # Get password
                import getpass
                password = getpass.getpass('Enter password for new superuser: ')
                
                with transaction.atomic():
                    user = User.objects.create_superuser(
                        username=username,
                        email=email,
                        password=password,
                        first_name='System',
                        last_name='Director',
                        role='admin'
                    )
                    
                    self.stdout.write(
                        self.style.SUCCESS(f'Successfully created superuser: {username}')
                    )
            else:
                self.stdout.write('Superuser already exists. Use --username to create another one.')
        else:
            self.stdout.write('\nUse --create flag to create a superuser if needed.')
