from django.db import models
from django.conf import settings


class Conversation(models.Model):
    participants = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name="inbox_conversations"
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-updated_at"]

    def __str__(self):
        names = ", ".join(p.username for p in self.participants.all())
        return f"Conversation({names})"

    def get_other_participant(self, user):
        return self.participants.exclude(id=user.id).first()


class Message(models.Model):
    conversation      = models.ForeignKey(Conversation, on_delete=models.CASCADE, related_name="messages")
    sender            = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="inbox_sent_messages")
    image             = models.ImageField(upload_to="inbox/", blank=True, null=True)
    audio             = models.FileField(upload_to="inbox/audio/", blank=True, null=True)
    content           = models.TextField(blank=True)
    created_at        = models.DateTimeField(auto_now_add=True)
    updated_at        = models.DateTimeField(auto_now=True)
    edited            = models.BooleanField(default=False)
    deleted_for_everyone = models.BooleanField(default=False)
    deleted_by        = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name="inbox_deleted_messages",
        blank=True
    )
    reply_to          = models.ForeignKey(
        "self", on_delete=models.SET_NULL,
        null=True, blank=True, related_name="replies"
    )
    forwarded_from    = models.ForeignKey(
        "self", on_delete=models.SET_NULL,
        null=True, blank=True, related_name="forwards"
    )
    read_by           = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name="inbox_read_messages",
        blank=True
    )

    class Meta:
        ordering = ["created_at"]

    def __str__(self):
        return f"{self.sender.username}: {self.content[:40]}"

    def is_read_by(self, user):
        return self.read_by.filter(id=user.id).exists()

    def is_deleted_by(self, user):
        return self.deleted_by.filter(id=user.id).exists()

class MessageReaction(models.Model):
    message = models.ForeignKey(Message, on_delete=models.CASCADE, related_name="reactions")
    user    = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="message_reactions")
    emoji   = models.CharField(max_length=10)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ["message", "user", "emoji"]
