# chat/tests/test_views.py
from django.urls import reverse
from rest_framework.test import APITestCase, APIClient
from rest_framework import status
from django.contrib.auth import get_user_model
from django.utils import timezone

from helpdesk.models import Ticket
from chat.models import Message

UserModel = get_user_model()

class MessageViewSetFunctionalTest(APITestCase):
    """Functional Test สำหรับ MessageViewSet"""

    def setUp(self):
        # 1. สร้าง Users
        self.agent = UserModel.objects.create_user(
            username="agent1",
            email="agent1@example.com",
            password="password123",
            is_staff=True
        )
        self.customer = UserModel.objects.create_user(
            username="customer1",
            email="customer1@example.com",
            password="password123",
            is_staff=False
        )

        # 2. สร้าง APIClient และ force_authenticate
        self.client_agent = APIClient()
        self.client_agent.force_authenticate(user=self.agent)

        self.client_customer = APIClient()
        self.client_customer.force_authenticate(user=self.customer)

        # 3. สร้าง Ticket ตัวอย่าง
        self.ticket = Ticket.objects.create(
            creator=self.customer,
            title="Chat Functional Test Ticket",
            last_message_at=timezone.now()
        )

    def test_message_list_and_create(self):
        """Test GET /messages/?ticket_id= และ POST /messages/"""
        url = reverse('chat-messages-list')  # ต้องตรงกับ router ของ MessageViewSet

        # GET messages → ต้องว่างก่อนสร้าง
        response = self.client_agent.get(url, {"ticket_id": self.ticket.id})
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 0)

        # POST ข้อความ Agent ส่ง
        post_data_agent = {
            "ticket": self.ticket.id,
            "content": "Hello from Agent",
            "message_type": "T"
        }

        response = self.client_agent.post(url, post_data_agent, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(response.data['content'], post_data_agent['content'])

        # ตรวจสอบ Ticket.is_read → Agent ส่งเอง → ต้อง True
        self.ticket.refresh_from_db()
        self.assertTrue(self.ticket.is_read)

        # POST ข้อความ Customer ส่ง
        post_data_customer = {
            "ticket": self.ticket.id,
            "content": "Customer: I need help!",
            "message_type": "T"
        }
        response = self.client_customer.post(url, post_data_customer, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        # ตรวจสอบ Ticket.is_read → Customer ส่ง → ต้อง False
        self.ticket.refresh_from_db()
        self.assertFalse(self.ticket.is_read)

        # GET messages → ต้องมี 2 ข้อความ ----
        response = self.client_agent.get(url, {"ticket_id": self.ticket.id})
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 2)
        self.assertEqual(response.data[0]['content'], "Hello from Agent")
        self.assertEqual(response.data[1]['content'], "Customer: I need help!")

        # ตรวจสอบว่า Message ใน DB ถูกสร้างครบ ----
        messages = Message.objects.filter(ticket=self.ticket).order_by('timestamp')
        self.assertEqual(messages.count(), 2)
        self.assertEqual(messages[0].content, "Hello from Agent")
        self.assertEqual(messages[1].content, "Customer: I need help!")
