from types import SimpleNamespace
from unittest.mock import MagicMock, patch

from django.test import SimpleTestCase
from rest_framework.test import APIRequestFactory

from apps.wf.views import TicketViewSet


class TicketAvailableActionsTests(SimpleTestCase):
    def setUp(self):
        self.request = APIRequestFactory().get('/api/wf/ticket/1/available_actions/')
        self.request.user = SimpleNamespace(id='user-1')
        self.view = TicketViewSet()
        self.ticket = SimpleNamespace(in_add_node=False)
        self.view.get_object = MagicMock(return_value=self.ticket)

    @patch('apps.wf.views.TransitionSerializer')
    @patch('apps.wf.views.WfService.get_ticket_transitions')
    @patch('apps.wf.views.WfService.ticket_handle_permission_check')
    def test_returns_transitions_when_user_can_handle(
            self, permission_check, get_transitions, serializer):
        permission_check.return_value = {
            'permission': True,
            'need_accept': False,
            'msg': '',
        }
        transitions = MagicMock()
        transitions.select_related.return_value = transitions
        get_transitions.return_value = transitions
        serializer.return_value.data = [{'id': 'transition-1', 'name': '同意'}]

        response = self.view.available_actions(self.request)

        self.assertTrue(response.data['permission'])
        self.assertFalse(response.data['need_accept'])
        self.assertEqual(
            response.data['transitions'],
            [{'id': 'transition-1', 'name': '同意'}],
        )

    @patch('apps.wf.views.TransitionSerializer')
    @patch('apps.wf.views.WfService.get_ticket_transitions')
    @patch('apps.wf.views.WfService.ticket_handle_permission_check')
    def test_hides_transitions_and_requests_accept_for_active_distribution(
            self, permission_check, get_transitions, serializer):
        permission_check.return_value = {
            'permission': False,
            'need_accept': True,
            'msg': '需要先接单再处理',
        }

        response = self.view.available_actions(self.request)

        self.assertFalse(response.data['permission'])
        self.assertTrue(response.data['need_accept'])
        self.assertEqual(response.data['message'], '需要先接单再处理')
        self.assertEqual(response.data['transitions'], [])
        get_transitions.assert_not_called()
        serializer.assert_not_called()
