from django.db import models
from Auth.models import Profile
from django.utils import timezone
import uuid

class Conversation(models.Model):
    """Modèle pour gérer les conversations entre utilisateurs"""
    CONVERSATION_TYPES = [
        ('private', 'Privée'),
        ('group', 'Groupe'),
    ]

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=255, blank=True, null=True)  # Nom pour les groupes
    conversation_type = models.CharField(max_length=10, choices=CONVERSATION_TYPES, default='private')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    last_activity = models.DateTimeField(default=timezone.now)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        if self.name:
            return f'Conversation: {self.name}'
        return f'Conversation {self.id}'

    def get_participants(self):
        return Profile.objects.filter(conversation_participants__conversation=self)

class ConversationParticipant(models.Model):
    """Modèle pour gérer les participants d'une conversation"""
    conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE, related_name='participants')
    participant = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='conversation_participants')
    joined_at = models.DateTimeField(auto_now_add=True)
    last_read_at = models.DateTimeField(default=timezone.now)
    is_active = models.BooleanField(default=True)

    class Meta:
        unique_together = ('conversation', 'participant')

    def __str__(self):
        return f'{self.participant.email} in {self.conversation.id}'

class Message(models.Model):
    """Modèle pour les messages instantanés"""
    MESSAGE_TYPES = [
        ('text', 'Texte'),
        ('file', 'Fichier'),
        ('image', 'Image'),
        ('system', 'Système'),
    ]

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE, related_name='messages')
    sender = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='sent_messages')
    content = models.TextField()
    message_type = models.CharField(max_length=10, choices=MESSAGE_TYPES, default='text')
    file_url = models.URLField(blank=True, null=True)  # Pour les fichiers/images
    file_name = models.CharField(max_length=255, blank=True, null=True)  # Nom original du fichier
    file_size = models.BigIntegerField(blank=True, null=True)  # Taille en bytes
    file_type = models.CharField(max_length=100, blank=True, null=True)  # MIME type
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_edited = models.BooleanField(default=False)
    is_deleted = models.BooleanField(default=False)

    class Meta:
        ordering = ['created_at']

    def __str__(self):
        return f'Message from {self.sender.email} at {self.created_at}'

class MessageRead(models.Model):
    """Modèle pour tracker les messages lus par chaque participant"""
    message = models.ForeignKey(Message, on_delete=models.CASCADE, related_name='read_by')
    participant = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='read_messages')
    read_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('message', 'participant')

    def __str__(self):
        return f'{self.participant.email} read {self.message.id}'

class UserPresence(models.Model):
    """Modèle pour gérer la présence des utilisateurs"""
    PRESENCE_STATUS = [
        ('online', 'En ligne'),
        ('away', 'Absent'),
        ('busy', 'Occupé'),
        ('offline', 'Hors ligne'),
    ]

    user = models.OneToOneField(Profile, on_delete=models.CASCADE, related_name='presence')
    status = models.CharField(max_length=10, choices=PRESENCE_STATUS, default='offline')
    last_seen = models.DateTimeField(default=timezone.now)
    is_typing_in = models.ForeignKey(Conversation, on_delete=models.SET_NULL, null=True, blank=True, related_name='typing_users')

    def __str__(self):
        return f'{self.user.email} - {self.status}'

# Ancien modèle conservé pour compatibilité
class Messagerie(models.Model):
    id = models.AutoField(primary_key=True)
    objet = models.CharField(max_length=200, default="", blank=True)
    emetteur = models.ForeignKey(Profile, on_delete=models.PROTECT, related_name='messages_envoyes')
    destinataire = models.ForeignKey(Profile, on_delete=models.PROTECT, related_name='messages_recus')
    corpus = models.CharField(max_length=200, default="", blank=True)
    date_envoi = models.DateTimeField(auto_now_add=True)  # Date d'envoi du message
    is_read = models.BooleanField(default=False)  # Statut lu/non lu
    conversation_id = models.CharField(max_length=100, blank=True, default="")  # Pour regrouper les messages par conversation

    def __str__(self):
        return f'Messagerie_{self.id}'