from django.contrib.auth import get_user_model
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

User = get_user_model()


class UserProfile(models.Model):
    """
    Perfiles extendidos del ecosistema E-Learning de Lo Justo con gestión de Roles y datos profesionales.
    """
    ROLE_CHOICES = (
        ('STUDENT', 'Alumno'),
        ('INSTRUCTOR', 'Profesor / Docente'),
        ('MANAGER', 'Coordinador'),
        ('ADMIN', 'Administrador'),
    )

    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile', verbose_name="Usuario")
    role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='STUDENT', verbose_name="Rol en la Plataforma")
    rut = models.CharField(max_length=20, blank=True, null=True, unique=True, verbose_name="RUT / DNI")
    phone = models.CharField(max_length=30, blank=True, verbose_name="Teléfono / Celular")
    company = models.CharField(max_length=150, blank=True, verbose_name="Empresa / Organización")
    position_title = models.CharField(max_length=150, blank=True, verbose_name="Cargo / Puesto de Trabajo")
    bio = models.TextField(blank=True, verbose_name="Biografía / Resumen Docente")
    avatar = models.ImageField(upload_to="users/avatars/", blank=True, null=True, verbose_name="Foto de Perfil")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="Fecha de Creación")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="Última Actualización")

    class Meta:
        verbose_name = "Perfil de Usuario"
        verbose_name_plural = "Perfiles de Usuario"
        ordering = ["-created_at"]

    def __str__(self):
        return f"{self.user.get_full_name() or self.user.username} ({self.get_role_display()})"

    @property
    def is_student(self):
        return self.role == 'STUDENT' or not self.role

    @property
    def is_instructor(self):
        return self.role in ['INSTRUCTOR', 'ADMIN'] or self.user.is_superuser

    @property
    def is_manager(self):
        return self.role in ['MANAGER', 'ADMIN'] or self.user.is_superuser

    @property
    def is_admin(self):
        return self.role == 'ADMIN' or self.user.is_superuser


@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)
    else:
        # Asegurar que el perfil exista
        UserProfile.objects.get_or_create(user=instance)
