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


def test_generic_page_persists_via_factory(home_page):
    page = GenericPageFactory(
        parent=home_page,
        title="Om oss",
        slug="om-oss",
        lead="<p>Ingress.</p>",
        body=[("paragraph", "<p>Body content.</p>")],
        pig="drink",
    )

    reloaded = GenericPage.objects.get(pk=page.pk)
    assert reloaded.title == "Om oss"
    assert reloaded.slug == "om-oss"
    assert "Ingress." in reloaded.lead
    assert reloaded.pig == "drink"
    assert reloaded.body[0].block_type == "paragraph"


def test_generic_page_allows_recursive_children(home_page):
    parent = GenericPageFactory(parent=home_page, title="Parent", slug="parent")
    child = GenericPageFactory(parent=parent, title="Child", slug="child")

    assert child.get_parent().specific == parent
    assert list(parent.get_children().specific()) == [child]


def test_graphql_generic_page_query(home_page, graphql_post):
    GenericPageFactory(
        parent=home_page,
        title="Om oss",
        slug="om-oss",
        lead="<p>Ingress text.</p>",
        body=[("paragraph", "<p>Body content.</p>")],
        pig="drink",
    )

    response, body = graphql_post(
        """
        query {
          page(slug: "om-oss", contentType: "generic.GenericPage") {
            title
            slug
            ... on GenericPage {
              lead
              pig
              body {
                blockType
                field
                ... on RichTextBlock {
                  value
                }
              }
            }
          }
        }
        """
    )

    assert response.status_code == 200
    assert "errors" not in body, body
    data = body["data"]["page"]
    assert data["title"] == "Om oss"
    assert data["slug"] == "om-oss"
    assert "Ingress text." in data["lead"]
    assert data["pig"] == "drink"
    assert data["body"][0]["blockType"] == "RichTextBlock"
    assert "Body content." in data["body"][0]["value"]
