import pytest
from rest_framework.test import APIClient
from apps.content.models import Article, Category
from apps.users.models import User
from django.utils import timezone

@pytest.mark.django_db
class TestContentAPI:
    
    def setup_method(self):
        self.client = APIClient()
        
        # Setup données
        self.user = User.objects.create_user(username='testauthor', password='password')
        self.cat_tech = Category.objects.create(name="Tech", slug="tech")
        self.cat_news = Category.objects.create(name="News", slug="news")
        
        # Article Publié (Tech)
        Article.objects.create(
            title="Article Publié", slug="publie",
            category=self.cat_tech, author=self.user,
            status='published', published_at=timezone.now(),
            content="Contenu"
        )
        # Article Brouillon (Tech)
        Article.objects.create(
            title="Article Brouillon", slug="brouillon",
            category=self.cat_tech, author=self.user,
            status='draft', # Ne doit pas apparaître
            content="Contenu"
        )
        # Article Publié (News)
        Article.objects.create(
            title="Article News", slug="news-art",
            category=self.cat_news, author=self.user,
            status='published', published_at=timezone.now(),
            content="Contenu"
        )

    def test_list_articles_only_published(self):
        """Vérifie que les brouillons sont masqués"""
        response = self.client.get('/api/blog/articles/')
        assert response.status_code == 200
        data = response.json()
        
        # On attend 2 articles (les publiés), pas 3
        assert data['count'] == 2 
        
    def test_filter_by_category_slug(self):
        """Vérifie le filtrage ?category=slug (si implémenté) ou via l'API categories"""
        # Testons l'endpoint catégorie directement
        response = self.client.get(f'/api/blog/categories/{self.cat_tech.slug}/')
        assert response.status_code == 200
        assert response.json()['slug'] == 'tech'

    def test_article_detail_structure(self):
        """Vérifie que le détail contient bien le contenu HTML"""
        response = self.client.get('/api/blog/articles/publie/')
        assert response.status_code == 200
        data = response.json()
        assert 'content' in data
        assert data['author']['username'] == 'testauthor'