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


class Conversation(models.Model):
    """Conversation between two users (buyer-vendor)"""
    participant1 = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='conversations_as_participant1'
    )
    participant2 = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='conversations_as_participant2'
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'conversations'
        unique_together = ('participant1', 'participant2')
        ordering = ['-updated_at']

    def __str__(self):
        return f"Conversation: {self.participant1} - {self.participant2}"

    @classmethod
    def get_or_create_conversation(cls, user1, user2):
        """Get existing conversation or create new one"""
        # Ensure consistent ordering to avoid duplicates
        if user1.id > user2.id:
            user1, user2 = user2, user1

        conversation, created = cls.objects.get_or_create(
            participant1=user1,
            participant2=user2
        )
        return conversation

    def get_other_participant(self, user):
        """Get the other participant in the conversation"""
        if self.participant1 == user:
            return self.participant2
        return self.participant1

    def is_participant(self, user):
        """Check if user is a participant"""
        return user == self.participant1 or user == self.participant2


class Message(models.Model):
    """Individual message in a conversation"""
    MESSAGE_TYPES = (
        ('text', 'Text'),
        ('image', 'Image'),
    )

    conversation = models.ForeignKey(
        Conversation,
        on_delete=models.CASCADE,
        related_name='messages'
    )
    sender = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='sent_messages'
    )
    message_type = models.CharField(max_length=10, choices=MESSAGE_TYPES, default='text')
    content = models.TextField(blank=True, null=True)  # For text messages
    image = models.ImageField(upload_to='chat_images/', blank=True, null=True)
    is_read = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'messages'
        ordering = ['created_at']

    def __str__(self):
        return f"Message from {self.sender} in {self.conversation}"

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        # Update conversation's updated_at
        self.conversation.save()


class BlockedUser(models.Model):
    """Track blocked users"""
    blocker = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='blocking'
    )
    blocked = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='blocked_by'
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'blocked_users'
        unique_together = ('blocker', 'blocked')

    def __str__(self):
        return f"{self.blocker} blocked {self.blocked}"

    @classmethod
    def is_blocked(cls, user1, user2):
        """Check if either user has blocked the other"""
        return cls.objects.filter(
            models.Q(blocker=user1, blocked=user2) |
            models.Q(blocker=user2, blocked=user1)
        ).exists()

    @classmethod
    def has_blocked(cls, blocker, blocked):
        """Check if blocker has blocked the blocked user"""
        return cls.objects.filter(blocker=blocker, blocked=blocked).exists()
