from django.test import TestCase
from django.contrib.auth import get_user_model
from unittest.mock import patch

from helpdesk.models import Ticket
from helpdesk.services.ticket_service import TicketService
from helpdesk.repositories.ticket_repository import TicketRepository
from unittest import skip

UserModel = get_user_model()

class AssignmentNotificationIntegrationTest(TestCase):

    def setUp(self):
        # 1. Setup Users (Agents)
        self.agent_1 = UserModel.objects.create_user(
            username='agent_one',
            email='agent1@test.com',
            password='p',
            is_staff=True
        )
        self.agent_2 = UserModel.objects.create_user(
            username='agent_two',
            email='agent2@test.com',
            password='p',
            is_staff=True
        )

        # 2. Setup Ticket
        self.ticket = Ticket.objects.create(
            creator=self.agent_1,
            title="Ticket for Assignment Test"
        )

        # 3. Setup Repository
        self.repo = TicketRepository()

    @patch("helpdesk.services.ticket_service.NotificationService")  # mock class
    def test_assignment_triggers_notification_call(self, MockNotificationService):
        """
        Integration Test: ตรวจสอบว่า assign_ticket_to_user() เรียก
        NotificationService.send_assignment_notification()
        """
        # Mock instance ของ NotificationService
        mock_notification_instance = MockNotificationService.return_value

        # Inject mock instance เข้าไปใน TicketService
        ticket_service = TicketService(
            ticket_repo=self.repo,
            notification_service=mock_notification_instance
        )

        # ACT: มอบหมาย ticket
        updated_ticket = ticket_service.assign_ticket_to_user(
            ticket_id=self.ticket.id,
            assignee_id=self.agent_2.id
        )

        # ASSERT 1: ตรวจสอบว่า Ticket ถูกมอบหมาย
        self.assertEqual(updated_ticket.assigned_to, self.agent_2)

        # ASSERT 2: ตรวจสอบว่า NotificationService ถูกเรียก
        mock_notification_instance.send_assignment_notification.assert_called_once_with(
            ticket_id=self.ticket.id,
            user_id=self.agent_2.id
        )
