from django.test import TestCase
from ..services.user_service import UserService
from ..models import BaseInfo
from ..utils.j_ulid_field import JULIDField

class TestUserSearch(TestCase):
    def setUp(self):
        # Create 10 users for testing
        self.users = []
        for i in range(10):
            user = BaseInfo.objects.create(
                username=f"testuser{i}",
                fullname=f"Test User {i}",
                nickname=f"testnick{i}",
                email=f"test{i}@example.com",
                phone=f"123456789{i}",
                user_info="{}",
                privacies="{}",
                is_using=True,
                uuid=JULIDField.get_u12()
            )
            self.users.append(user)

    def test_user_search_by_id_list(self):
        # Test searching users by a list of user IDs
        user_id_list = [user.id for user in self.users[:5]]  # Search for the first 5 users
        result, err = UserService.user_search(user_id_list=user_id_list)
        self.assertEqual(err, None)
        self.assertEqual(len(result["data"]), 5)  # Expect 5 users in the result

    def test_user_search_by_search_params(self):
        # Test searching users by search parameters
        search_params = {"username": "testuser1"}
        result, err = UserService.user_search(search_params=search_params)
        self.assertEqual(err, None)
        self.assertEqual(len(result["data"]), 1)  # Expect 1 user in the result
        self.assertEqual(result["data"][0]["username"], "testuser1")

    def test_user_search_by_email(self):
        # Test searching users by email
        search_params = {"email": "test1@example.com"}
        result, err = UserService.user_search(search_params=search_params)
        self.assertEqual(err, None)
        self.assertEqual(len(result["data"]), 1)  # Expect 1 user in the result
        self.assertEqual(result["data"][0]["email"], "test1@example.com")

    def test_user_search_by_fullname(self):
        # Test searching users by fullname
        search_params = {"fullname": "Test User 2"}
        result, err = UserService.user_search(search_params=search_params)
        self.assertEqual(err, None)
        self.assertEqual(len(result["data"]), 1)  # Expect 1 user in the result
        self.assertEqual(result["data"][0]["fullname"], "Test User 2")

    def test_user_search_pagination(self):
        # Test searching users with pagination
        search_params = {}
        result, err = UserService.user_search(search_params=search_params, page=1, page_size=5)
        self.assertEqual(err, None)
        self.assertEqual(len(result["data"]), 5)  # Expect 5 users in the result
        self.assertEqual(result["pagination"]["total"], 10)  # Total users should be 10
        self.assertEqual(result["pagination"]["page"], 1)  # Current page should be 1
        self.assertEqual(result["pagination"]["page_size"], 5)  # Page size should be 5

    def test_user_search_order_by_username(self):
        # Test searching users with ordering by username
        search_params = {}
        result, err = UserService.user_search(search_params=search_params, order_by="username")
        self.assertEqual(err, None)
        self.assertEqual(len(result["data"]), 10)  # Expect all 10 users in the result
        # Check if the users are ordered by username
        usernames = [user["username"] for user in result["data"]]
        self.assertEqual(usernames, sorted(usernames))

    def test_user_search_order_by_fullname_desc(self):
        # Test searching users with ordering by fullname in descending order
        search_params = {}
        result, err = UserService.user_search(search_params=search_params, order_by="-fullname")
        self.assertEqual(err, None)
        self.assertEqual(len(result["data"]), 10)  # Expect all 10 users in the result
        # Check if the users are ordered by fullname in descending order
        fullnames = [user["fullname"] for user in result["data"]]
        self.assertEqual(fullnames, sorted(fullnames, reverse=True))

    def test_user_search_with_filter_fields(self):
        # Test searching users with specific filter fields
        search_params = {}
        filter_fields = ["username", "email"]
        result, err = UserService.user_search(search_params=search_params, filter_fields=filter_fields)
        self.assertEqual(err, None)
        self.assertEqual(len(result["data"]), 10)  # Expect all 10 users in the result
        # Check if only the specified fields are returned
        for user in result["data"]:
            self.assertIn("username", user)
            self.assertIn("email", user)
            self.assertNotIn("fullname", user)

    def test_user_search_with_need_map(self):
        # Test searching users with need_map=True
        search_params = {}
        result, err = UserService.user_search(search_params=search_params, need_map=True)
        self.assertEqual(err, None)
        self.assertEqual(len(result["data"]), 10)  # Expect all 10 users in the result
        # Check if the result is a dictionary with user_id as keys
        self.assertIsInstance(result["data"], dict)
        for user_id, user_info in result["data"].items():
            self.assertIn("user_id", user_info)
            self.assertEqual(user_id, str(user_info["user_id"]))

    def test_user_search_with_invalid_page(self):
        # Test searching users with an invalid page number
        search_params = {}
        result, err = UserService.user_search(search_params=search_params, page=100, page_size=5)
        self.assertEqual(err, "页码超出范围")
        self.assertEqual(result, [])  # Expect an empty result