import pytest
from rest_framework.test import APIClient
from apps.pages.models import Page
from apps.sections.models import Section

@pytest.mark.django_db
class TestSectionPolymorphism:
    
    def setup_method(self):
        self.client = APIClient()
        self.page = Page.objects.create(title="Mixed Page", slug="mixed", is_published=True)

    def test_mixed_sections_order_and_types(self):
        """
        Vérifie qu'une page avec des sections variées renvoie le bon JSON
        dans le bon ordre.
        """
        # 1. On crée un Hero (Ordre 1)
        Section.objects.create(
            page=self.page,
            type="hero_simple",
            order=1,
            data={"title": "Je suis le Hero"}
        )
        
        # 2. On crée des Stats (Ordre 2)
        Section.objects.create(
            page=self.page,
            type="stats",
            order=2,
            data={"items": [{"value": "100", "label": "Tests"}]}
        )

        # Appel API
        response = self.client.get(f'/api/pages/{self.page.slug}/')
        assert response.status_code == 200
        data = response.json()
        
        sections = data['sections']
        assert len(sections) == 2
        
        # Vérification Ordre et Type
        assert sections[0]['type'] == 'hero_simple'
        assert sections[0]['content']['title'] == "Je suis le Hero"
        
        assert sections[1]['type'] == 'stats'
        assert sections[1]['content']['items'][0]['value'] == "100"

    def test_inactive_section_is_hidden(self):
        """Une section désactivée ne doit pas apparaître dans l'API"""
        Section.objects.create(
            page=self.page,
            type="text_block",
            is_active=False, # <--- DÉSACTIVÉ
            data={"content": "Caché"}
        )
        
        response = self.client.get(f'/api/pages/{self.page.slug}/')
        data = response.json()
        
        assert len(data['sections']) == 0