from django.db import models
from pxy_openai.models import OpenAIAssistant  # Import the OpenAIAssistant model

class WhatsAppBot(models.Model):
    name = models.CharField(max_length=255, unique=True, help_text="Name of the WhatsApp bot.")
    phone_number_id = models.CharField(max_length=255, help_text="Phone number ID for the bot.")
    graph_api_token = models.TextField(help_text="Graph API token for the bot.")
    webhook_verify_token = models.CharField(max_length=255, help_text="Token for verifying the webhook.")
    is_active = models.BooleanField(default=False, help_text="Is this bot currently active?")
    assistant = models.ForeignKey(
        OpenAIAssistant,
        on_delete=models.CASCADE,
        related_name="whatsapp_bots",
        help_text="The OpenAI assistant associated with this WhatsApp bot.",
    )

    def __str__(self):
        return self.name
    

class Conversation(models.Model):
    bot = models.ForeignKey(
        'WhatsAppBot',
        on_delete=models.CASCADE,
        related_name='conversations'
    )
    user_number = models.CharField(max_length=32)
    started_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.user_number} @ {self.started_at:%Y-%m-%d %H:%M}"

class Message(models.Model):
    DIRECTION_CHOICES = [
        ('in', 'In'),
        ('out', 'Out'),
    ]
    conversation = models.ForeignKey(
        Conversation,
        on_delete=models.CASCADE,
        related_name='messages'
    )
    direction = models.CharField(max_length=4, choices=DIRECTION_CHOICES)
    content = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)
    response_time_ms = models.IntegerField(null=True, blank=True)

    def __str__(self):
        return f"[{self.direction}] {self.content[:30]}…"

