from django.contrib.auth import get_user_model
from django.core.management import BaseCommand, CommandError

from help.models import HelpUser

User = get_user_model()


class Command(BaseCommand):
    help = "Reset offline account reset code for existing users"

    def add_arguments(self, parser):
        parser.add_argument("users", nargs='+', type=str)

    def handle(self, *args, **options):
        for name in options["users"]:
            try:
                user = User.objects.get(username=name)
            except User.DoesNotExist:
                raise CommandError(f'User {name} does not exist')

            help_user = user.helpuser
            if help_user is None:
                help_user = HelpUser.objects.create(email_address=user.email)

            help_user.generate_offline_account_code()
            help_user.save()

            self.stdout.write(f"generated new offline account reset code {help_user.offline_account_code} for {name}")
