from django.db import models
from django.contrib.auth.models import (
    AbstractBaseUser,
    BaseUserManager,
    PermissionsMixin,
)
from phonenumber_field.modelfields import PhoneNumberField

class Role(models.Model):
    name = models.CharField(max_length=250, unique=True)

    def __str__(self):
        return self.name

class UserManager(BaseUserManager):
    def create(self, **kwargs):
        return self.create_user(email=kwargs.pop("email", None), **kwargs)

    def create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError("Email is required")
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password=None, **extra_fields):
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)
        extra_fields.setdefault("is_active", True)
        return self.create_user(email, password, **extra_fields)


def get_default_role():
    from users.models import Role
    from django.db import OperationalError, ProgrammingError
    try:
        role, _ = Role.objects.get_or_create(name="Unassigned")
        return role.pk
    except (OperationalError, ProgrammingError):
        return None


class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    phone = PhoneNumberField(unique=True)
    name = models.CharField(max_length=250)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    role = models.ForeignKey("Role", on_delete=models.PROTECT, default=get_default_role)

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["name", "phone"]

    objects = UserManager()

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        from django.urls import reverse

        return reverse("users:detail", kwargs={"pk": self.pk})


