from django.contrib.auth.models import BaseUserManager
from django.db import models
from django.utils import timezone


class UsersQuerySet(models.QuerySet):
    def only_real(self):
        return self.filter(exclude_in_queries=False)


class UserManager(BaseUserManager.from_queryset(UsersQuerySet)):
    use_for_related_fields = True

    def _create_user(
        self, username: str, email, password, is_staff, is_superuser, **extra_fields
    ):
        """
        Creates and saves a User with the given username, email and password.
        """
        now = timezone.now()
        email = self.normalize_email(email)
        user = self.model(
            username=username,
            email=email,
            is_staff=is_staff,
            is_active=True,
            is_superuser=is_superuser,
            last_login=now,
            date_joined=now,
            **extra_fields
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, username: str, email=None, password=None, **extra_fields):
        return self._create_user(
            username, email, password, False, False, **extra_fields
        )

    def create_superuser(self, username: str, email, password, **extra_fields):
        return self._create_user(username, email, password, True, True, **extra_fields)
