"""apps.api 单元测试：预览专用接口 `page_preview`（apps/api/urls.py 的
PagePreviewAPIViewSet），覆盖 §2.7/§2.15 描述的"仅凭有效 content_type+token
才能读取草稿快照"行为。"""
import pytest
from rest_framework.test import APIClient

pytestmark = pytest.mark.django_db


@pytest.fixture
def preview_token(home_page):
    """为 home_page 生成一条预览快照记录，返回可用于查询接口的 token。"""
    preview = home_page.create_page_preview()
    preview.save()
    return preview.token


def test_page_preview_returns_draft_snapshot_for_valid_token(home_page, preview_token):
    client = APIClient()
    response = client.get(
        "/api/v2/page_preview/",
        {"content_type": "home.homepage", "token": preview_token},
    )

    assert response.status_code == 200
    assert response.data["title"] == home_page.title


def test_page_preview_returns_404_for_unknown_token(home_page):
    client = APIClient()
    response = client.get(
        "/api/v2/page_preview/",
        {"content_type": "home.homepage", "token": "does-not-exist"},
    )

    assert response.status_code == 404


def test_page_preview_returns_404_for_mismatched_content_type(home_page, preview_token):
    """token 是为 home.homepage 生成的，用错误的 content_type 查询应查不到记录。"""
    client = APIClient()
    response = client.get(
        "/api/v2/page_preview/",
        {"content_type": "blog.blogpage", "token": preview_token},
    )

    assert response.status_code == 404
