"""
Management command to create a test loan officer for testing
"""
from django.core.management.base import BaseCommand
from django.utils import timezone
from users.models import CustomUser, Branch


class Command(BaseCommand):
    help = 'Creates a test loan officer for testing permissions'

    def add_arguments(self, parser):
        parser.add_argument(
            '--email',
            type=str,
            default='testofficer@example.com',
            help='Email for the test loan officer'
        )
        parser.add_argument(
            '--password',
            type=str,
            default='testpass123',
            help='Password for the test loan officer'
        )

    def handle(self, *args, **options):
        email = options['email']
        password = options['password']
        
        # Check if officer already exists
        if CustomUser.objects.filter(email=email).exists():
            self.stdout.write(self.style.WARNING(f'Loan officer with email {email} already exists'))
            officer = CustomUser.objects.get(email=email)
            self.stdout.write(self.style.SUCCESS(f'Existing officer: {officer.get_full_name()} (ID: {officer.id})'))
            return
        
        # Get or create a branch
        branch = Branch.objects.first()
        if not branch:
            branch = Branch.objects.create(
                name='Test Branch',
                code='TST001',
                location='Test Location',
                is_active=True
            )
            self.stdout.write(self.style.SUCCESS(f'Created test branch: {branch.name}'))
        
        # Create the loan officer
        try:
            officer = CustomUser.objects.create(
                username='testofficer',
                first_name='Test',
                last_name='Officer',
                email=email,
                phone_number='+254712345678',
                role='loan_officer',
                status='active',
                branch=branch,
            )
            officer.set_password(password)
            officer.save()
            
            self.stdout.write(self.style.SUCCESS(f'Successfully created loan officer: {officer.get_full_name()}'))
            self.stdout.write(self.style.SUCCESS(f'Email: {email}'))
            self.stdout.write(self.style.SUCCESS(f'Password: {password}'))
            self.stdout.write(self.style.SUCCESS(f'Officer ID: {officer.id}'))
            self.stdout.write(self.style.SUCCESS(f'Branch: {branch.name}'))
            self.stdout.write(self.style.SUCCESS(f'\nYou can now log in and test permissions!'))
            
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'Error creating loan officer: {e}'))

