from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandParser

from mentor.contrib.staff.client import staff_api
from mentor.staff.services import load_staff_profile
from mentor.staff.utils import lookup_field

User = get_user_model()


class Command(BaseCommand):
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument("username", nargs="+", type=str)
        parser.add_argument(
            "--force", action="store_true", dest="force_load", default=False
        )

    def load_users(self, **options):
        usernames = options.get("username")
        force_load = options.get("force_load")

        if not len(usernames):
            return

        params = {
            "_limit": len(usernames),
            "_fields": "uid,login,work_email,name.first.ru,name.last.ru",
            "login": ",".join(usernames),
        }

        response = staff_api.persons.get(**params)

        for person in response["result"]:
            user, created = User.objects.get_or_create(
                username=person["login"],
                defaults={
                    "yauid": person["uid"],
                    "email": person["work_email"],
                    "first_name": lookup_field(person, "name.first.ru"),
                    "last_name": lookup_field(person, "name.last.ru"),
                },
            )
            if created:
                load_staff_profile(user.pk)
                self.stdout.write(f"User {user.username} loaded")
            else:
                self.stdout.write(f"User {user.username} already exists")
                if force_load:
                    load_staff_profile(user.pk)
                    self.stdout.write("Staff profile was refreshed")

    def handle(self, *args, **options):
        self.load_users(**options)
        self.stdout.write("Done\n")
