from chat.repositories.message_repository import MessageRepository
from helpdesk.services.ticket_service import ticket_service
from chat.serializers.message_serializers import MessageSerializer
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.db import transaction

from helpdesk.services.ticket_service import ticket_service as helpdesk_ticket_service

class MessageService:
    def __init__(self, message_repo=None, ticket_service=None):
        # รองรับ DI สำหรับ unit test
        self.message_repo = message_repo or MessageRepository()
        self.ticket_service = ticket_service  # ไม่ใช่ global อีกต่อไป

    def get_ticket_messages(self, ticket_id: int):
        return self.message_repo.get_messages_by_ticket(ticket_id)

    @transaction.atomic
    def create_and_send_message(self, ticket_id, sender, content, message_type):
        sender_is_agent = sender.is_staff

        ticket_ref = self.ticket_service.get_ticket_ref(ticket_id)

        new_message = self.message_repo.create_message(
            ticket_id=ticket_ref["id"],
            sender=sender,
            content=content,
            message_type=message_type
        )

        self.ticket_service.update_ticket_on_new_message(
            ticket_id=ticket_ref["id"],
            content=new_message.content,
            timestamp=new_message.timestamp,
            sender_is_agent=sender_is_agent
        )

        self._send_realtime_update(new_message)
        return new_message

    def _send_realtime_update(self, message):
        channel_layer = get_channel_layer()
        data = MessageSerializer(message).data
        ticket_group_name = f'ticket_{message.ticket_id}'

        async_to_sync(channel_layer.group_send)(
            ticket_group_name,
            {'type': 'chat.message', 'message': data}
        )

# สร้าง instance สำหรับใช้งานจริง
message_service = MessageService(ticket_service=helpdesk_ticket_service)