"""Tests for the Document Versions API endpoint.

GET /api/v1/document/versions/{content_hash}
  — lists all document versions sharing the same content_hash,
    filtered by the current user's ACL permissions.
"""

import pytest
from httpx import AsyncClient


@pytest.mark.asyncio
class TestDocumentVersions:
    """GET /api/v1/document/versions/{content_hash}."""

    async def test_versions_requires_auth(self, client: AsyncClient, api_prefix: str):
        """Unauthenticated request should be rejected."""
        resp = await client.get(f"{api_prefix}/document/versions/abc123hash")
        assert resp.status_code in (401, 403)

    async def test_versions_returns_200(self, client: AsyncClient, api_prefix: str, auth_headers: dict):
        """Valid content_hash (even if no match) should return 200 with structure."""
        resp = await client.get(
            f"{api_prefix}/document/versions/nonexistent_hash_xyz",
            headers=auth_headers,
        )
        assert resp.status_code == 200
        body = resp.json()
        assert body["content_hash"] == "nonexistent_hash_xyz"
        assert "versions" in body
        assert "total" in body
        assert isinstance(body["versions"], list)
        assert body["total"] == 0

    async def test_versions_response_fields(self, client: AsyncClient, api_prefix: str, auth_headers: dict):
        """Verify response structure matches VersionListResponse schema."""
        resp = await client.get(
            f"{api_prefix}/document/versions/some_hash_value",
            headers=auth_headers,
        )
        assert resp.status_code == 200
        body = resp.json()
        # Schema requires these top-level keys
        assert set(body.keys()) >= {"content_hash", "versions", "total"}

    async def test_versions_acl_filtering(
        self,
        client: AsyncClient,
        api_prefix: str,
        auth_headers: dict,
        user_headers: dict,
    ):
        """Different users should potentially see different versions for the same hash.

        Both should return 200 (even if empty), but admin (broader ACL) may see
        more versions than a regular user.
        """
        hash_val = "acl_test_hash_xyz"
        resp_admin = await client.get(
            f"{api_prefix}/document/versions/{hash_val}",
            headers=auth_headers,
        )
        assert resp_admin.status_code == 200

        resp_user = await client.get(
            f"{api_prefix}/document/versions/{hash_val}",
            headers=user_headers,
        )
        assert resp_user.status_code == 200

        # admin should see >= as many versions as regular user
        admin_total = resp_admin.json()["total"]
        user_total = resp_user.json()["total"]
        assert admin_total >= user_total
