"""
apps/business/network_chat/models.py

Lightweight in-system chat between distributors identified by their distributor_code
or referral_code. No mobile/email is ever exposed to the other party.
"""
import uuid
from django.db import models
from django.conf import settings


class ChatConversation(models.Model):
    """
    A conversation thread between two distributors.
    Participants are identified by their DistributorID records.
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    initiator = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='initiated_conversations',
    )
    recipient = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='received_conversations',
    )
    # Distributor IDs that anchor the conversation (the "identity" both sides see)
    initiator_distributor_code = models.CharField(max_length=50, db_index=True)
    recipient_distributor_code = models.CharField(max_length=50, db_index=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        # Only one conversation per direction (initiator→recipient distributor pair)
        unique_together = ('initiator_distributor_code', 'recipient_distributor_code')
        ordering = ['-updated_at']
        verbose_name = 'Chat Conversation'
        verbose_name_plural = 'Chat Conversations'

    def __str__(self):
        return f"{self.initiator_distributor_code} ↔ {self.recipient_distributor_code}"


class ChatMessage(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    conversation = models.ForeignKey(
        ChatConversation,
        on_delete=models.CASCADE,
        related_name='messages',
    )
    sender = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='sent_chat_messages',
    )
    sender_distributor_code = models.CharField(max_length=50)
    body = models.TextField(max_length=2000)
    is_read = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['created_at']
        verbose_name = 'Chat Message'
        verbose_name_plural = 'Chat Messages'

    def __str__(self):
        return f"[{self.sender_distributor_code}] {self.body[:60]}"
