"""Round-trip tests for wagtail-headless-preview token resolution via grapple."""

from generic.models import GenericPage
from tests.conftest import GenericPageFactory


def test_generic_page_preview_token_resolves_draft(home_page, graphql_post):
    """A minted preview token returns the unsaved draft via grapple's page(token: …)."""
    # Publish a baseline so there's a live revision to diverge from.
    page = GenericPageFactory(parent=home_page, title="Original title", slug="generic-preview")

    # Mutate in-memory to simulate unsaved editor state, then mint a token.
    # create_page_preview() snapshots the current to_json() into a PagePreview row.
    page.title = "Edited title (draft)"
    preview = page.create_page_preview()

    response, body = graphql_post(
        """
        query previewPage($token: String!) {
          page: page(token: $token) {
            __typename
            ... on GenericPage {
              title
            }
          }
        }
        """,
        variables={"token": preview.token},
    )

    assert response.status_code == 200
    assert "errors" not in body, body
    assert body["data"]["page"]["__typename"] == "GenericPage"
    assert body["data"]["page"]["title"] == "Edited title (draft)"

    # Live revision is unchanged — token short-circuits the published query.
    assert GenericPage.objects.get(pk=page.pk).title == "Original title"
