# -*- encoding: utf-8 -*-

import logging

from django.contrib.auth.models import BaseUserManager

log = logging.getLogger(__name__)


class DiscordUserOAuth2Manager(BaseUserManager):
    """
    Manager for the DiscordUser class.
    """

    def create_user(self, discord_user_data: dict, **extra_fields):
        """
        Create a user from their discord data.

        Parameters
        ----------
        discord_user_data : dict
            The raw discord user data

        Returns
        -------
        DiscordUser
            The newly created DiscordUser instance.
        """

        username = discord_user_data.get("username")
        log.debug("creating new user: %s", username)

        discord_user_data.update(extra_fields)
        user = discord_user_data  # shorthand

        log.debug(user)

        return self.create(
            id=user["id"],
            username=user["username"],
            global_name=user["global_name"],
            avatar=user["avatar"],
            public_flags=user["public_flags"],
            flags=user["flags"],
            locale=user["locale"],
            mfa_enabled=user["mfa_enabled"],
            access_token=user["access_token"],
            **extra_fields
        )

    def create_superuser(self, discord_user_data: dict, **extra_fields):
        """
        Create a user from their discord data, but also make them a superuser.
        """

        username = discord_user_data.get("username")
        log.debug("creating new superuser: %s", username)

        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)
        extra_fields.setdefault("is_active", True)

        if not extra_fields.get("is_staff"):
            raise ValueError("Superuser must have is_staff=True")
        
        if not extra_fields.get("is_superuser"):
            raise ValueError("Superuser must have is_staff=True")
        
        return self.create_user(discord_user_data, **extra_fields)
