"""
Tests for the UserProfile pattern -- extending UserSubject with
app-specific fields via a OneToOneField profile model.
"""

import pytest

from example_app.models import UserProfile


@pytest.mark.django_db
class TestUserProfile:
    """Verify the profile model and its auto-creation signal."""

    def test_profile_auto_created_on_user_creation(self, user1):
        """A UserProfile is automatically created when a UserSubject is saved."""
        assert hasattr(user1, "profile")
        assert isinstance(user1.profile, UserProfile)

    def test_profile_fields_default_to_blank(self, user1):
        """Profile fields default to empty strings."""
        assert user1.profile.bio == ""
        assert user1.profile.avatar_url == ""

    def test_profile_fields_are_editable(self, user1):
        """Profile fields can be updated and persisted."""
        user1.profile.bio = "Hello, world!"
        user1.profile.avatar_url = "https://example.com/avatar.png"
        user1.profile.save()

        user1.profile.refresh_from_db()
        assert user1.profile.bio == "Hello, world!"
        assert user1.profile.avatar_url == "https://example.com/avatar.png"

    def test_profile_str(self, user1):
        """The __str__ method returns a readable representation."""
        assert str(user1.profile) == f"Profile of {user1.username}"

    def test_profile_deleted_with_user(self, user1):
        """Deleting the user cascades to the profile."""
        profile_pk = user1.profile.pk
        user1.delete()
        assert not UserProfile.objects.filter(pk=profile_pk).exists()

    def test_each_user_gets_own_profile(self, user1, user2):
        """Each user has a distinct profile instance."""
        assert user1.profile.pk != user2.profile.pk
