from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase

from rest_framework import status
from rest_framework.test import APIClient

from core.models import Tag
from recipe.serializers import TagSerializer



TAGS_URL = reverse('recipe:tag-list')



class PublicTagsApiTests(TestCase):
    """Testea las API tags publicas."""

    def setUp(self):
        self.client = APIClient()
    

    def test_login_required(self):
        """Testea que sea necesario iniciar sesion para retornar tags."""
        res = self.client.get(TAGS_URL)
        self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)



class PrivateTagsApiTests(TestCase):
    """TEstea las API tags que requieren autenticacion"""

    def setUp(self):
        self.user = get_user_model().objects.create_user(
            'test@francorueta.com',
            'pass1234'
        )
        self.client = APIClient()
        self.client.force_authenticate(user=self.user)
    
    def test_retrieve_tags(self):
        """Testea retornar las tags"""
        Tag.objects.create(user=self.user,name='Vegano')
        Tag.objects.create(user=self.user,name='Postre')

        res = self.client.get(TAGS_URL)

        tags = Tag.objects.all().order_by('-name')
        serializer = TagSerializer
        serializer = TagSerializer(tags, many=True)

        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serializer.data)
    
    def test_tags_limited_to_user(self):
        """Testea que las tags retornadas sean SOLO para el usuario logeado."""
        user2 = get_user_model().objects.create_user(
            'test2@francorueta.com',
            'pass1234'
        )
        Tag.objects.create(user=user2,name='Calorico')
        tag = Tag.objects.create(user=self.user, name='Coccion rapida')
        
        res = self.client.get(TAGS_URL)

        self.assertEqual(res.status_code,status.HTTP_200_OK)
        self.assertEqual(len(res.data),1)
        self.assertEqual(res.data[0]['name'], tag.name)
    

