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


class Message(models.Model):
    MESSAGE_TYPES = [
        ("text", "Text"),
        ("image", "Image"),
        ("system", "System"),
    ]

    room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name="messages")
    sender = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        related_name="sent_messages"
    )
    content = models.TextField(blank=True)
    image = models.ImageField(upload_to="chat/images/", blank=True, null=True)
    message_type = models.CharField(max_length=10, choices=MESSAGE_TYPES, default="text")

    reply_to = models.ForeignKey(
        "self", on_delete=models.SET_NULL,
        null=True, blank=True,
        related_name="replies"
    )

    reactions = models.JSONField(default=dict, blank=True)

    is_deleted = models.BooleanField(default=False)
    is_reported = models.BooleanField(default=False)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["created_at"]

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


class MessageReport(models.Model):
    REASON_CHOICES = [
        ("spam", "Spam"),
        ("hate", "Hate speech"),
        ("abuse", "Abuse"),
        ("misinformation", "Misinformation"),
        ("other", "Other"),
    ]

    message = models.ForeignKey(Message, on_delete=models.CASCADE, related_name="reports")
    reported_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    reason = models.CharField(max_length=20, choices=REASON_CHOICES)
    details = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    resolved = models.BooleanField(default=False)

    class Meta:
        unique_together = ("message", "reported_by")

    def __str__(self):
        return f"Report on msg {self.message.id} by {self.reported_by.username}"