from django.test import TestCase
from django.contrib.auth import get_user_model
from django.utils import timezone

from helpdesk.repositories.ticket_repository import TicketRepository
from helpdesk.models import Ticket, TicketStatus

UserModel = get_user_model()

class TicketRepositoryTest(TestCase):

    def setUp(self):
        self.repo = TicketRepository()

        # สร้าง Users
        self.creator = UserModel.objects.create_user(
            username='repo_creator',
            email='repo_creator@test.com',
            password='p'
        )

        self.assigned_user = UserModel.objects.create_user(
            username='repo_assignee',
            email='repo_assignee@test.com',
            password='p'
        )

        # สร้าง Tickets
        self.ticket1 = Ticket.objects.create(
            creator=self.creator,
            assigned_to=self.assigned_user,
            title="Test Ticket 1",
            last_message_at=timezone.now(),
            last_message_content="Initial message 1",
            status=TicketStatus.OPEN,
            is_read=True,
        )

        self.ticket2 = Ticket.objects.create(
            creator=self.creator,
            title="Test Ticket 2",
            last_message_at=timezone.now(),
            last_message_content="Initial message 2",
            status=TicketStatus.OPEN,
            is_read=True,
        )

    def test_get_unified_inbox_list_uses_select_related(self):
        """ตรวจสอบว่าการ Query ใช้ select_related() เพื่อลดจำนวน Query (แก้ปัญหา N+1)"""
        with self.assertNumQueries(1):
            tickets = list(self.repo.get_unified_inbox_list())
            for ticket in tickets:
                _ = ticket.creator.username

        self.assertEqual(len(tickets), 2)
