from django.contrib.auth.models import BaseUserManager
from django.utils.translation import gettext_lazy as _

class AccountManager(BaseUserManager):
    """
    Custom user model manager where email is the unique identifier
    for authentication instead of usernames.
    """
    
    # Flag to indicate this manager should be used in migrations.
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """
        Create and save a User with the given email and password.
        """
        # Ensure that an email is provided; raise a ValueError otherwise.
        if not email:
            raise ValueError('The given Email must be set') 
        # Normalize the email address.
        email = self.normalize_email(email) 
        # Create a new user instance with the normalized email and other provided fields.
        user = self.model(email=email.lower(), **extra_fields) 
        # Set the password for the user.
        user.set_password(password) 
        # Save the user using the database connection specified.
        user.save(using=self._db)
        # 
        return user
    
    def create_user(self, email, password=None, **extra_fields):
        """
        Create and save a regular User with the given email and password.
        """
        # Ensure the user is not staff or superuser by default.
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        # Create and save the user using the _create_user method. 
        return self._create_user(email, password, **extra_fields)
    
    def create_superuser(self, email, password=None, **extra_fields):
        """
        Create and save a SuperUser with the given email and password.
        """
        # Set default values for admin-related fields if not provided.
        extra_fields.setdefault("is_admin", True)
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)
        extra_fields.setdefault("is_active", True) 
        # Ensure the superuser has is_admin and is_superuser set to True.
        if extra_fields.get("is_admin") is not True:
            raise ValueError(_("Superuser must have is_admin=True."))
        if extra_fields.get("is_superuser") is not True:
            raise ValueError(_("Superuser must have is_superuser=True.")) 
        # Create and save the superuser using the _create_user method.
        return self._create_user(email, password, **extra_fields)
