"""Tests for the Document API endpoints."""

import pytest
from httpx import AsyncClient


@pytest.mark.asyncio
class TestDocumentDetail:
    """GET /api/v1/document/{doc_id} — document detail view."""

    async def test_detail_requires_auth(self, client: AsyncClient, api_prefix: str):
        resp = await client.get(f"{api_prefix}/document/some-doc-id")
        assert resp.status_code in (401, 403)

    async def test_detail_nonexistent(self, client: AsyncClient, api_prefix: str, auth_headers: dict):
        resp = await client.get(
            f"{api_prefix}/document/nonexistent-doc-id-99999",
            headers=auth_headers,
        )
        assert resp.status_code == 404

    async def test_detail_valid_doc(self, client: AsyncClient, api_prefix: str, auth_headers: dict):
        """If any document has been ingested, we should be able to fetch it.
        This test may be skipped if no documents are in the index.
        """
        # First, list docs from admin logs to find one
        logs_resp = await client.get(
            f"{api_prefix}/admin/ingest-logs",
            params={"page": 1, "page_size": 1},
        )
        if logs_resp.status_code != 200:
            pytest.skip("Admin logs not available")

        records = logs_resp.json().get("records", [])
        if not records:
            pytest.skip("No documents ingested yet")

        doc_id = records[0].get("doc_id")
        if not doc_id:
            pytest.skip("No doc_id in ingest log record")

        resp = await client.get(
            f"{api_prefix}/document/{doc_id}",
            headers=auth_headers,
        )
        # May be 200 or 403 depending on ACL
        assert resp.status_code in (200, 403, 404)
        if resp.status_code == 200:
            body = resp.json()
            assert "doc_id" in body
            assert "title" in body


@pytest.mark.asyncio
class TestDocumentGraph:
    """GET /api/v1/document/{doc_id}/graph — doc knowledge graph."""

    async def test_graph_requires_auth(self, client: AsyncClient, api_prefix: str):
        resp = await client.get(f"{api_prefix}/document/some-id/graph")
        assert resp.status_code in (401, 403)

    async def test_graph_nonexistent(self, client: AsyncClient, api_prefix: str, auth_headers: dict):
        resp = await client.get(
            f"{api_prefix}/document/nonexistent-doc-99/graph",
            headers=auth_headers,
        )
        # Should return 200 with empty graph or 404
        assert resp.status_code in (200, 404)


@pytest.mark.asyncio
class TestDocumentDelete:
    """DELETE /api/v1/document/{doc_id} — delete doc (auth required)."""

    async def test_delete_requires_auth(self, client: AsyncClient, api_prefix: str):
        resp = await client.delete(f"{api_prefix}/document/some-doc-id")
        assert resp.status_code in (401, 403)
