from django.db import models
from django.core.validators import RegexValidator


class CommunicationSession(models.Model):
    """
    Masked communication session using Twilio Conversations.
    
    Enables staff and customers to communicate via SMS/chat without
    exposing personal phone numbers. Twilio routes messages through
    a proxy number.
    """
    
    # Link to event
    event = models.OneToOneField(
        'schedule.Event',
        on_delete=models.CASCADE,
        related_name='communication_session'
    )
    
    # Twilio identifiers
    twilio_conversation_sid = models.CharField(
        max_length=255,
        unique=True,
        db_index=True,
        help_text="Twilio Conversation SID"
    )
    
    # Session status
    is_active = models.BooleanField(
        default=True,
        db_index=True,
        help_text="Whether the conversation is active"
    )
    
    # Phone validation regex (E.164 format)
    phone_regex = RegexValidator(
        regex=r'^\+?1?\d{9,15}$',
        message="Phone number must be in E.164 format (+1234567890)"
    )
    
    # Secure phone storage
    # NOTE: In production, consider encrypting these fields
    staff_phone = models.CharField(
        max_length=20,
        validators=[phone_regex],
        help_text="Staff member's phone number (E.164 format)"
    )
    
    customer_phone = models.CharField(
        max_length=20,
        validators=[phone_regex],
        help_text="Customer's phone number (E.164 format)"
    )
    
    #  Localization
    language_code = models.CharField(
        max_length=10,
        default='en',
        help_text="Language preference for SMS templates (en/es/fr/de)"
    )
    
    # Participant SIDs (for cleanup)
    staff_participant_sid = models.CharField(
        max_length=255,
        blank=True,
        help_text="Twilio Participant SID for staff"
    )
    
    customer_participant_sid = models.CharField(
        max_length=255,
        blank=True,
        help_text="Twilio Participant SID for customer"
    )
    
    # Metadata
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    closed_at = models.DateTimeField(
        null=True,
        blank=True,
        help_text="When the conversation was closed"
    )
    
    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['is_active', 'created_at']),
        ]
    
    def __str__(self):
        status = "Active" if self.is_active else "Closed"
        return f"Session for {self.event.title} ({status})"
    
    @property
    def message_count(self):
        """
        Get total message count (would require Twilio API call).
        Stub for future implementation.
        """
        # TODO: Implement via Twilio API
        return None
