"""
Tests for Themis signal handlers.
"""
from django.contrib.auth import get_user_model
from django.test import TestCase

from themis.models import UserProfile

User = get_user_model()


class SignalTest(TestCase):
    """Tests for auto-creation and saving of UserProfile via signals."""

    def test_profile_created_on_user_create(self):
        """Creating a user automatically creates a UserProfile."""
        user = User.objects.create_user(username="newuser", password="pass123")
        self.assertTrue(UserProfile.objects.filter(user=user).exists())

    def test_profile_is_accessible(self):
        """Profile is accessible via user.profile reverse relation."""
        user = User.objects.create_user(username="reluser", password="pass123")
        self.assertIsNotNone(user.profile)
        self.assertEqual(user.profile.user, user)

    def test_profile_saved_on_user_save(self):
        """Saving the user also saves the profile (save_user_profile signal)."""
        user = User.objects.create_user(username="saveuser", password="pass123")
        profile = user.profile
        profile.home_timezone = "America/New_York"
        profile.save()

        # Save user triggers save_user_profile
        user.first_name = "Updated"
        user.save()

        profile.refresh_from_db()
        self.assertEqual(profile.home_timezone, "America/New_York")

    def test_multiple_users_each_get_profile(self):
        """Each user gets their own distinct profile."""
        user1 = User.objects.create_user(username="user1", password="pass123")
        user2 = User.objects.create_user(username="user2", password="pass123")
        self.assertNotEqual(user1.profile.pk, user2.profile.pk)
        self.assertEqual(UserProfile.objects.count(), 2)

    def test_profile_not_duplicated_on_user_resave(self):
        """Re-saving a user does not create a duplicate profile."""
        user = User.objects.create_user(username="resaveuser", password="pass123")
        user.save()
        user.save()
        self.assertEqual(UserProfile.objects.filter(user=user).count(), 1)
