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

from apps.blog.models import BlogIndexPage, BlogPage

pytestmark = pytest.mark.django_db


@pytest.fixture
def blog_index(home_page):
    index = BlogIndexPage(title="博客", slug="blog", intro="技术与行业洞察")
    home_page.add_child(instance=index)
    return index


def test_blog_page_can_be_created_under_index(blog_index):
    post = BlogPage(
        title="文章一",
        slug="post-1",
        published_at=timezone.now(),
        intro="摘要一",
    )
    blog_index.add_child(instance=post)

    assert BlogPage.objects.live().descendant_of(blog_index).count() == 1


def test_blog_page_supports_tags(blog_index):
    post = BlogPage(
        title="文章一",
        slug="post-1",
        published_at=timezone.now(),
    )
    blog_index.add_child(instance=post)

    post.tags.add("Django", "Wagtail")
    post.save()

    post.refresh_from_db()
    assert {t.name for t in post.tags.all()} == {"Django", "Wagtail"}


def test_blog_index_context_orders_by_published_at_desc(blog_index):
    older = BlogPage(
        title="较早的文章",
        slug="older-post",
        published_at=timezone.now() - timezone.timedelta(days=5),
    )
    blog_index.add_child(instance=older)

    newer = BlogPage(
        title="较新的文章",
        slug="newer-post",
        published_at=timezone.now(),
    )
    blog_index.add_child(instance=newer)

    context = blog_index.get_context(request=None)
    titles = [p.title for p in context["posts"]]

    assert titles == ["较新的文章", "较早的文章"]


def test_blog_index_context_excludes_draft_posts(blog_index):
    live_post = BlogPage(
        title="已发布文章",
        slug="live-post",
        published_at=timezone.now(),
    )
    blog_index.add_child(instance=live_post)

    draft_post = BlogPage(
        title="草稿文章",
        slug="draft-post",
        published_at=timezone.now(),
        live=False,
    )
    blog_index.add_child(instance=draft_post)

    context = blog_index.get_context(request=None)
    titles = [p.title for p in context["posts"]]

    assert "已发布文章" in titles
    assert "草稿文章" not in titles
