from django.contrib.auth.models import AbstractUser
from django.db import models
from django.contrib.sessions.models import Session
from django.utils import timezone


def document_upload_path(instance, filename):
    return f'documents/user_{instance.user.id}/{filename}'


class User(AbstractUser):
    email = models.EmailField(unique=True)
    
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name']
    
    def __str__(self):
        return self.email
    
    def force_logout(self):
        user_sessions = []
        for session in Session.objects.filter(expire_date__gte=timezone.now()):
            session_data = session.get_decoded()
            if str(self.pk) == str(session_data.get('_auth_user_id')):
                user_sessions.append(session.pk)
        Session.objects.filter(pk__in=user_sessions).delete()
    
    def save(self, *args, **kwargs):
        if self.pk:
            try:
                old_user = User.objects.get(pk=self.pk)
                if old_user.is_active and not self.is_active:
                    self.force_logout()
            except User.DoesNotExist:
                pass
        super().save(*args, **kwargs)


class CustomerProfile(models.Model):
    class CustomerType(models.TextChoices):
        PERSONAL = 'personal', 'Personal'
        BUSINESS = 'business', 'Business'
    
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    customer_type = models.CharField(max_length=20, choices=CustomerType.choices, default=CustomerType.PERSONAL)
    
    job_title = models.CharField(max_length=100, blank=True)
    phone_number = models.CharField(max_length=20)
    
    company_name = models.CharField(max_length=255, blank=True)
    company_legal_name = models.CharField(max_length=255, blank=True)
    company_email = models.EmailField(blank=True)
    vat_tax_number = models.CharField(max_length=50, blank=True)
    
    street_address = models.CharField(max_length=255)
    city = models.CharField(max_length=100)
    country = models.CharField(max_length=100, default='United Arab Emirates')
    state_province = models.CharField(max_length=100, blank=True)
    zip_code = models.CharField(max_length=20)
    
    business_permit = models.FileField(upload_to=document_upload_path, blank=True)
    commercial_trading_license = models.FileField(upload_to=document_upload_path, blank=True)
    vat_registration_certificate = models.FileField(upload_to=document_upload_path, blank=True)
    owner_passport_copy = models.FileField(upload_to=document_upload_path, blank=True)
    national_id = models.FileField(upload_to=document_upload_path, blank=True)
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'Customer Profile'
        verbose_name_plural = 'Customer Profiles'
    
    def __str__(self):
        return f"{self.user.email} - {self.customer_type}"
    
    @property
    def is_business(self):
        return self.customer_type == self.CustomerType.BUSINESS
    
    @property
    def is_personal(self):
        return self.customer_type == self.CustomerType.PERSONAL
    