from apps.blog.models import Post, Tag

URL = "/api/v1/backoffice/posts/"


def test_create_post_with_new_tags_and_category(staff_api, api, db):
    category = staff_api.post(
        "/api/v1/backoffice/blog-categories/", {"name": "Conseils"}, format="json"
    ).json()
    assert category["slug"] == "conseils"
    payload = {
        "title": "Bien choisir son hébergement",
        "excerpt": "Nos conseils.",
        "content": "<p>Texte</p>",
        "category": "conseils",
        "tags": ["Hébergement", "SEO", "seo"],
    }
    response = staff_api.post(URL, payload, format="json")
    assert response.status_code == 201
    data = response.json()
    assert data["slug"] == "bien-choisir-son-hebergement"
    assert data["tag_names"] == ["Hébergement", "SEO"]
    public = api.get(f"/api/v1/posts/{data['slug']}/").json()
    assert public["category"] == {"name": "Conseils", "slug": "conseils"}


def test_existing_tag_is_reused_and_list_replaced(staff_api, db):
    Tag.objects.create(name="SEO", slug="seo")
    post = staff_api.post(
        URL, {"title": "A", "excerpt": "B", "tags": ["seo"]}, format="json"
    ).json()
    assert Tag.objects.count() == 1
    staff_api.patch(f"{URL}{post['id']}/", {"tags": []}, format="json")
    assert Post.objects.get(pk=post["id"]).tags.count() == 0


def test_unpublish_hides_post(staff_api, api, db):
    post = staff_api.post(URL, {"title": "Caché", "excerpt": "B"}, format="json").json()
    assert api.get("/api/v1/posts/cache/").status_code == 200
    staff_api.patch(f"{URL}{post['id']}/", {"is_published": False}, format="json")
    assert api.get("/api/v1/posts/cache/").status_code == 404
    assert staff_api.delete(f"{URL}{post['id']}/").status_code == 204


def test_blog_requires_staff(api, db):
    assert api.get(URL).status_code == 403
    assert api.post("/api/v1/backoffice/blog-categories/", {"name": "X"}).status_code == 403
