from django.core.management.base import BaseCommand
from rog.models import CustomUser
from django.contrib.auth import authenticate

class Command(BaseCommand):
    help = 'Check user authentication'

    def add_arguments(self, parser):
        parser.add_argument('email', type=str, help='User email to check')
        parser.add_argument('--password', type=str, help='Password to test', default='')

    def handle(self, *args, **options):
        email = options['email']
        password = options.get('password', '')
        
        self.stdout.write(f'Checking user: {email}')
        
        try:
            user = CustomUser.objects.get(email=email)
            self.stdout.write(f'✅ User found: {user.email}')
            self.stdout.write(f'   Active: {user.is_active}')
            self.stdout.write(f'   Has password: {bool(user.password)}')
            self.stdout.write(f'   Password hash start: {user.password[:30]}...')
            
            if password:
                self.stdout.write(f'\n🔐 Testing authentication with provided password...')
                auth_user = authenticate(username=email, password=password)
                if auth_user:
                    self.stdout.write('✅ Authentication successful')
                else:
                    self.stdout.write('❌ Authentication failed')
                    
        except CustomUser.DoesNotExist:
            self.stdout.write(f'❌ User does not exist: {email}')
        except Exception as e:
            self.stdout.write(f'❌ Error: {e}')
