"""apps.cases 单元测试：页面树结构与列表排序。"""
import pytest
from django.utils import timezone

from apps.cases.models import CaseStudyIndexPage, CaseStudyPage

pytestmark = pytest.mark.django_db


@pytest.fixture
def case_index(home_page):
    index = CaseStudyIndexPage(title="客户案例", slug="cases", intro="客户的成功案例")
    home_page.add_child(instance=index)
    return index


def test_case_study_page_can_be_created_under_index(case_index):
    case = CaseStudyPage(
        title="某集团数字化转型",
        slug="some-group",
        client_name="某集团",
        industry="制造业",
        published_at=timezone.now(),
    )
    case_index.add_child(instance=case)

    assert CaseStudyPage.objects.live().descendant_of(case_index).count() == 1


def test_case_index_context_orders_by_published_at_desc(case_index):
    older = CaseStudyPage(
        title="案例一",
        slug="case-1",
        client_name="客户一",
        published_at=timezone.now() - timezone.timedelta(days=10),
    )
    case_index.add_child(instance=older)

    newer = CaseStudyPage(
        title="案例二",
        slug="case-2",
        client_name="客户二",
        published_at=timezone.now(),
    )
    case_index.add_child(instance=newer)

    context = case_index.get_context(request=None)
    titles = [c.title for c in context["case_studies"]]

    assert titles == ["案例二", "案例一"]
