# users/models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.utils import timezone

class CustomUserManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError('The Email field must be set')
        # if not extra_fields.get('first_name'):
        #     raise ValueError('The First Name field must be set')
        # if not extra_fields.get('last_name'):
        #     raise ValueError('The Last Name field must be set')
        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_verified', True)
        return self.create_user(email, password, **extra_fields)

class CustomUser(AbstractBaseUser):
    email = models.EmailField(unique=True)
    first_name = models.CharField(max_length=150)
    last_name = models.CharField(max_length=150)
    phone_number = models.CharField(max_length=20, blank=True, null=True)
    country_name = models.CharField(max_length=100, blank=True, null=True)
    is_verified = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    gender = models.CharField(max_length=10, choices=[('male', 'Male'), ('female', 'Female'), ('other', 'Other')], blank=True, null=True)
    music_sound = models.BooleanField(default=True)

    objects = CustomUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name']

    def __str__(self):
        return self.email

class Device(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='devices')
    device_id = models.CharField(max_length=255, blank=True, null=True)
    user_agent = models.CharField(max_length=255)
    ip_address = models.GenericIPAddressField()
    last_login = models.DateTimeField(auto_now=True)

    class Meta:
        # Ensure unique combination of user and device_id (only when device_id is not null/empty)
        constraints = [
            models.UniqueConstraint(fields=['user', 'device_id'], name='unique_user_device_id')
        ]

    def __str__(self):
        return f"{self.user.email} - {self.device_id or self.user_agent} ({self.ip_address})"
        

class OTP(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    otp = models.CharField(max_length=4)
    created_at = models.DateTimeField(null=True, blank=True)  # Allow null initially
    expires_at = models.DateTimeField(null=True, blank=True)

    def save(self, *args, **kwargs):
        if not self.created_at:  # Set created_at if not already set
            self.created_at = timezone.now()
        if not self.expires_at:  # Set expires_at based on created_at
            self.expires_at = self.created_at + timezone.timedelta(minutes=10)
        super().save(*args, **kwargs)
