"""
Integration tests for the Pages REST API (/api/pages).
"""

import pytest


@pytest.mark.django_db
class TestPagesAPI:
    BASE = "/api/pages"

    def test_list_empty(self, api_client):
        r = api_client.get(f"{self.BASE}")
        assert r.status_code == 200
        assert r.json()["count"] == 0

    def test_create_page(self, api_client):
        r = api_client.post(f"{self.BASE}", {"url": "https://example.com"}, format="json")
        assert r.status_code == 201
        data = r.json()
        assert data["url"] == "https://example.com"
        assert "id" in data

    def test_list_after_create(self, api_client):
        api_client.post(f"{self.BASE}", {"url": "https://example.com"}, format="json")
        api_client.post(f"{self.BASE}", {"url": "https://github.com"}, format="json")
        r = api_client.get(f"{self.BASE}")
        assert r.json()["count"] == 2

    def test_get_page_detail(self, api_client):
        created = api_client.post(
            f"{self.BASE}", {"url": "https://example.com"}, format="json"
        ).json()
        r = api_client.get(f"{self.BASE}/{created['id']}")
        assert r.status_code == 200
        assert r.json()["url"] == "https://example.com"

    def test_update_page_title(self, api_client):
        created = api_client.post(
            f"{self.BASE}", {"url": "https://example.com"}, format="json"
        ).json()
        r = api_client.patch(
            f"{self.BASE}/{created['id']}",
            {"title": "Updated Title"},
            format="json",
        )
        assert r.status_code == 200
        assert r.json()["title"] == "Updated Title"

    def test_delete_page(self, api_client):
        created = api_client.post(
            f"{self.BASE}", {"url": "https://example.com"}, format="json"
        ).json()
        r = api_client.delete(f"{self.BASE}/{created['id']}")
        assert r.status_code == 204
        r2 = api_client.get(f"{self.BASE}/{created['id']}")
        assert r2.status_code == 404

    def test_create_page_missing_url_returns_400(self, api_client):
        r = api_client.post(f"{self.BASE}", {}, format="json")
        assert r.status_code == 400
