from django.db import models
from django.conf import settings
from helpdesk.models import Ticket # อ้างอิงข้ามโดเมน

class Message(models.Model):
    """โมเดลสำหรับเก็บข้อความสนทนาในแต่ละ Ticket"""

    TICKET_MESSAGE = 'T'
    PRIVATE_NOTE = 'P'
    MESSAGE_TYPES = [
        (TICKET_MESSAGE, 'Ticket Message (Public)'),
        (PRIVATE_NOTE, 'Private Note (Internal)')
    ]

    ticket = models.ForeignKey(
        Ticket,
        on_delete=models.CASCADE,
        related_name='messages' # เชื่อมโยงกับ Ticket ที่เพิ่งสร้าง
    )
    sender = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True, blank=True,
        related_name='sent_messages'
    )
    content = models.TextField()
    message_type = models.CharField(
        max_length=1,
        choices=MESSAGE_TYPES,
        default=TICKET_MESSAGE
    )
    timestamp = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['timestamp']

    def __str__(self):
        return f"Msg {self.id} on TKT {self.ticket_id}"