from django.db import models
import uuid
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin

class UserPanelisManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError('E-pasts ir obligāts')
        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('role', 'superadmin')
        extra_fields.setdefault('is_active', True)
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        return self.create_user(email, password, **extra_fields)

class UserPanelis(AbstractBaseUser, PermissionsMixin):
    ROLE_CHOICES = (
        ('superadmin', 'Super Admin'),
        ('admin', 'Admin'),
        ('member', 'Member'),
        ('klients', 'Klients'),
    )

    email = models.EmailField(unique=True)
    full_name = models.CharField(max_length=255)
    role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='klients')
    
    # Drošības lauki
    is_active = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    
    # Juridiskie apstiprinājumi
    terms_accepted = models.BooleanField(default=False)
    accepted_at = models.DateTimeField(null=True, blank=True)

    # 2FA un Bota lauki
    otp_code = models.CharField(max_length=6, blank=True, null=True)
    otp_created_at = models.DateTimeField(blank=True, null=True, verbose_name='OTP izveidots')
    otp_attempts = models.IntegerField(default=0, verbose_name='OTP mēģinājumi')
    telegram_id = models.BigIntegerField(blank=True, null=True, unique=True)
    
    # 🎯 LABOTS: Noņemts 'default', pievienots 'blank=True'. 
    # Tagad Django vairs neprasīs jautājumus migrācijas laikā!
    telegram_link_code = models.UUIDField(editable=False, unique=True, null=True, blank=True)
    
    objects = UserPanelisManager()
    
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['full_name']

    def __str__(self):
        return self.email

    # 🎯 JAUNUMS: Pārrakstām saglabāšanas funkciju. 
    # Ja lietotājam nav Telegram koda, mēs to uzģenerējam šeit!
    def save(self, *args, **kwargs):
        if not self.telegram_link_code:
            self.telegram_link_code = uuid.uuid4()
        super().save(*args, **kwargs)