from django.contrib.auth.models import UserManager as DjangoUserManager


class UserManager(DjangoUserManager):
    """Keep the existing username API; canonicalize emails for authentication."""

    @classmethod
    def normalize_email(cls, email):
        return (email or "").strip().lower()

    def _create_user(self, username, email, password, **extra_fields):
        if not email or not email.strip():
            raise ValueError("Email is required.")
        return super()._create_user(username, self.normalize_email(email), password, **extra_fields)

    def get_by_natural_key(self, email):
        return self.get(email__iexact=self.normalize_email(email))

    def create_superuser(self, username, email=None, password=None, **extra_fields):
        extra_fields.setdefault("is_email_verified", True)
        return super().create_superuser(username, email, password, **extra_fields)
