from django.test import TestCase
from django.contrib.auth import get_user_model
from rest_framework.test import APIClient
from rest_framework import status
from django.urls import reverse
from posts.models import Post
from users.models import BlockedUser

User = get_user_model()

class BlockingVisibilityTestCase(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.user_A = User.objects.create_user(username='UserA', email='a@e.com', password='pw')
        self.user_B = User.objects.create_user(username='UserB', email='b@e.com', password='pw')
        self.user_C = User.objects.create_user(username='UserC', email='c@e.com', password='pw')

        # Create posts
        self.post_a = Post.objects.create(content='Post by A', created_by=self.user_A, audience='PUBLIC')
        self.post_b = Post.objects.create(content='Post by B', created_by=self.user_B, audience='PUBLIC')

    def test_block_visibility_mutual(self):
        """
        If A blocks B:
        - A should NOT see B's posts
        - B should NOT see A's posts
        """
        BlockedUser.objects.create(blocker=self.user_A, blocked=self.user_B)

        # Test A's view
        self.client.force_authenticate(user=self.user_A)
        response = self.client.get(reverse('list_posts'))
        contents = [p['content'] for p in response.data['results']]
        self.assertNotIn('Post by B', contents)

        # Test B's view
        self.client.force_authenticate(user=self.user_B)
        response = self.client.get(reverse('list_posts'))
        contents = [p['content'] for p in response.data['results']]
        self.assertNotIn('Post by A', contents)

    def test_block_does_not_affect_others(self):
        """Block between A and B should not affect C"""
        BlockedUser.objects.create(blocker=self.user_A, blocked=self.user_B)

        self.client.force_authenticate(user=self.user_C)
        response = self.client.get(reverse('list_posts'))
        contents = [p['content'] for p in response.data['results']]
        self.assertIn('Post by A', contents)
        self.assertIn('Post by B', contents)
