from django.test import TestCase
from unittest.mock import MagicMock
from django.utils import timezone
from helpdesk.services.ticket_service import TicketService
from helpdesk.models import TicketStatus, Ticket
from django.contrib.auth import get_user_model

UserModel = get_user_model()

class TicketServiceStatusTest(TestCase):

    def setUp(self):
        self.mock_repo = MagicMock()
        self.service = TicketService(ticket_repo=self.mock_repo)

        # Mock Ticket Object
        self.mock_ticket = Ticket(
            id=1,
            title="Test Ticket",
            status=TicketStatus.OPEN,
            last_message_at=timezone.now(),
            last_message_content="Initial message",
            is_read=True,
        )

        self.mock_repo.get_ticket_by_id.return_value = self.mock_ticket

    def test_allow_status_change_from_open_to_inprogress(self):
        new_status = TicketStatus.IN_PROGRESS

        # Mock update_ticket return value
        updated_ticket = Ticket(
            id=1,
            title="Test Ticket",
            status=new_status,
            last_message_at=timezone.now(),
            last_message_content="Initial message",
            is_read=True,
        )
        self.mock_repo.update_ticket.return_value = updated_ticket

        # ACT
        result = self.service.update_ticket_status(1, new_status)

        # ASSERT
        self.assertEqual(result.status, new_status)
        self.mock_repo.update_ticket.assert_called_once()

    def test_prevent_status_change_from_closed_to_open(self):
        self.mock_ticket.status = TicketStatus.CLOSED

        with self.assertRaises(ValueError) as ctx:
            self.service.update_ticket_status(
                ticket_id=1,
                new_status=TicketStatus.OPEN
            )

        self.assertIn("Cannot transition from CLOSED to OPEN", str(ctx.exception))
        self.mock_repo.update_ticket.assert_not_called()
