from django.db import models
from django.urls import reverse


class ResakaProfile(models.Model):
    display_name = models.CharField(max_length=80)
    handle = models.SlugField(max_length=80, unique=True)
    status_text = models.CharField(max_length=140, blank=True)
    avatar_color = models.CharField(max_length=7, default="#22D3EE")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["display_name"]

    def __str__(self):
        return f"{self.display_name} (@{self.handle})"


class Conversation(models.Model):
    starter = models.ForeignKey(
        ResakaProfile,
        on_delete=models.CASCADE,
        related_name="started_conversations",
    )
    recipient = models.ForeignKey(
        ResakaProfile,
        on_delete=models.CASCADE,
        related_name="received_conversations",
    )
    subject = models.CharField(max_length=120, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-updated_at", "-created_at"]

    def __str__(self):
        return self.subject or f"{self.starter.display_name} → {self.recipient.display_name}"

    def counterpart_for(self, profile):
        if profile and self.starter_id == profile.id:
            return self.recipient
        return self.starter

    def get_absolute_url(self):
        return reverse("conversation_detail", args=[self.pk])


class Message(models.Model):
    conversation = models.ForeignKey(
        Conversation,
        on_delete=models.CASCADE,
        related_name="messages",
    )
    author = models.ForeignKey(
        ResakaProfile,
        on_delete=models.CASCADE,
        related_name="messages",
    )
    body = models.TextField()
    reaction = models.CharField(max_length=8, blank=True)
    is_read = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["created_at"]

    def __str__(self):
        preview = (self.body[:30] + "…") if len(self.body) > 30 else self.body
        return f"{self.author.display_name}: {preview}"
