from django.db import models

class Fanpage(models.Model):
    name = models.CharField(max_length=255)
    page_id = models.CharField(max_length=255, unique=True)
    access_token = models.TextField()
    verify_token = models.CharField(max_length=255, help_text="Token for Facebook Webhook verification")
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

class Flow(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    fanpage = models.ForeignKey(Fanpage, on_delete=models.CASCADE, related_name='flows')
    is_default = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.name} ({self.fanpage.name})"

class Node(models.Model):
    NODE_TYPES = (
        ('text', 'Text Message'),
        ('buttons', 'Buttons/Quick Replies'),
        ('image', 'Image'),
    )
    flow = models.ForeignKey(Flow, on_delete=models.CASCADE, related_name='nodes')
    name = models.CharField(max_length=255, help_text="Internal name for this step")
    node_type = models.CharField(max_length=20, choices=NODE_TYPES, default='text')
    content = models.JSONField(help_text="Stores the message text, button labels, etc.")
    is_start_node = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.name} [{self.node_type}]"

class Edge(models.Model):
    flow = models.ForeignKey(Flow, on_delete=models.CASCADE, related_name='edges')
    source_node = models.ForeignKey(Node, on_delete=models.CASCADE, related_name='outgoing_edges')
    target_node = models.ForeignKey(Node, on_delete=models.CASCADE, related_name='incoming_edges')
    condition = models.CharField(max_length=255, help_text="Keyword or button payload that triggers this edge")

    def __str__(self):
        return f"{self.source_node.name} -> {self.target_node.name} on '{self.condition}'"

class ChatSession(models.Model):
    psid = models.CharField(max_length=255, help_text="Facebook Page Scoped ID of the user")
    fanpage = models.ForeignKey(Fanpage, on_delete=models.CASCADE)
    current_node = models.ForeignKey(Node, on_delete=models.SET_NULL, null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('psid', 'fanpage')

class MessageLog(models.Model):
    session = models.ForeignKey(ChatSession, on_delete=models.CASCADE, related_name='logs')
    sender_type = models.CharField(max_length=10, choices=(('user', 'User'), ('bot', 'Bot')))
    message_text = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)