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


class Discussion(models.Model):
    BOARD_TYPE_CHOICES = [
        ('lead', 'Lead Discussion'),
        ('project', 'Project Discussion'),
        ('task', 'Task Discussion'),
    ]

    lead = models.ForeignKey(
        'leads.Lead', on_delete=models.CASCADE, null=True, blank=True,
        related_name='discussions'
    )
    project = models.ForeignKey(
        'projects.Project', on_delete=models.CASCADE, null=True, blank=True,
        related_name='discussions'
    )
    task = models.ForeignKey(
        'tasks.Task', on_delete=models.CASCADE, null=True, blank=True,
        related_name='discussions'
    )
    board_type = models.CharField(max_length=10, choices=BOARD_TYPE_CHOICES)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        app_label = 'discussions'

    def __str__(self):
        if self.lead:
            return f'Lead: {self.lead.title}'
        if self.project:
            return f'Project: {self.project.name}'
        if self.task:
            return f'Task: {self.task.title}'
        return f'Discussion #{self.id}'


class Message(models.Model):
    discussion = models.ForeignKey(Discussion, on_delete=models.CASCADE, related_name='messages')
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    content = models.TextField(help_text='Rich text HTML')
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='replies')
    is_pinned = models.BooleanField(default=False)
    is_deleted = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        app_label = 'discussions'
        ordering = ['created_at']

    def __str__(self):
        return f'Message by {self.author} at {self.created_at}'


class MessageAttachment(models.Model):
    message = models.ForeignKey(Message, on_delete=models.CASCADE, related_name='attachments')
    file = models.FileField(upload_to='message_attachments/')
    file_name = models.CharField(max_length=255, blank=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        app_label = 'discussions'

    def __str__(self):
        return self.file_name


class MessageReaction(models.Model):
    EMOJI_CHOICES = [
        ('👍', '👍'), ('✅', '✅'), ('❌', '❌'), ('🔥', '🔥'), ('👀', '👀'),
    ]

    message = models.ForeignKey(Message, on_delete=models.CASCADE, related_name='reactions')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    emoji = models.CharField(max_length=5, choices=EMOJI_CHOICES)

    class Meta:
        app_label = 'discussions'
        unique_together = ['message', 'user', 'emoji']

    def __str__(self):
        return f'{self.user} reacted {self.emoji}'
