"""
API Integration tests for OpenNotion backend.
Validates all API endpoints work correctly end-to-end.
"""
import pytest
from httpx import AsyncClient


class TestMemosApiIntegration:
    """Integration tests for memos API."""

    @pytest.mark.asyncio
    async def test_list_memos_returns_valid_structure(self, async_client: AsyncClient):
        """Test that list memos returns proper structure."""
        response = await async_client.get("/api/v1/memos")
        
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        
        if len(data) > 0:
            memo = data[0]
            assert "id" in memo
            assert "content" in memo
            assert "creator_id" in memo

    @pytest.mark.asyncio
    async def test_get_memo_by_id(self, async_client: AsyncClient):
        """Test getting a single memo by ID."""
        # First list memos
        list_response = await async_client.get("/api/v1/memos")
        assert list_response.status_code == 200
        
        memos = list_response.json()
        if len(memos) > 0:
            memo_id = memos[0]["id"]
            
            # Get single memo
            response = await async_client.get(f"/api/v1/memos/{memo_id}")
            assert response.status_code == 200
            
            memo = response.json()
            assert memo["id"] == memo_id

    @pytest.mark.asyncio
    async def test_list_memos_with_tag_filter(self, async_client: AsyncClient):
        """Test filtering memos by tag."""
        response = await async_client.get("/api/v1/memos?tag=test")
        
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)


class TestUserStatsApiIntegration:
    """Integration tests for user stats API."""

    @pytest.mark.asyncio
    async def test_user_stats_returns_valid_structure(self, async_client: AsyncClient):
        """Test that user stats returns proper structure."""
        response = await async_client.get("/api/v1/users/1/stats")
        
        assert response.status_code == 200
        data = response.json()
        
        assert "tagCount" in data or "tag_count" in data
        assert "memoDisplayTimestamps" in data or "memo_display_timestamps" in data

    @pytest.mark.asyncio
    async def test_user_stats_tag_count_is_dict(self, async_client: AsyncClient):
        """Test that tag count is a dictionary."""
        response = await async_client.get("/api/v1/users/1/stats")
        
        assert response.status_code == 200
        data = response.json()
        
        tag_count = data.get("tagCount") or data.get("tag_count", {})
        assert isinstance(tag_count, dict)


class TestVersionsApiIntegration:
    """Integration tests for versions API."""

    @pytest.mark.asyncio
    async def test_versions_endpoint_exists(self, async_client: AsyncClient):
        """Test that versions endpoint is accessible."""
        # First get a memo
        memos_response = await async_client.get("/api/v1/memos")
        
        if memos_response.status_code == 200 and len(memos_response.json()) > 0:
            memo_id = memos_response.json()[0]["id"]
            
            response = await async_client.get(f"/api/v1/memos/{memo_id}/versions")
            
            assert response.status_code == 200
            data = response.json()
            assert "versions" in data
            assert "total" in data

    @pytest.mark.asyncio
    async def test_versions_returns_empty_for_unedited_memo(self, async_client: AsyncClient):
        """Test that versions is empty for unedited memo."""
        memos_response = await async_client.get("/api/v1/memos")
        
        if memos_response.status_code == 200 and len(memos_response.json()) > 0:
            memo_id = memos_response.json()[0]["id"]
            
            response = await async_client.get(f"/api/v1/memos/{memo_id}/versions")
            
            assert response.status_code == 200
            data = response.json()
            # Versions may be empty if never edited
            assert isinstance(data["versions"], list)


class TestCommentsApiIntegration:
    """Integration tests for comments API."""

    @pytest.mark.asyncio
    async def test_list_comments_endpoint(self, async_client: AsyncClient):
        """Test that comments endpoint works."""
        memos_response = await async_client.get("/api/v1/memos")
        
        if memos_response.status_code == 200 and len(memos_response.json()) > 0:
            memo_id = memos_response.json()[0]["id"]
            
            response = await async_client.get(f"/api/v1/memos/{memo_id}/comments")
            
            # Should return 200 or valid error
            assert response.status_code in [200, 404]


class TestHealthCheck:
    """Health check and basic functionality tests."""

    @pytest.mark.asyncio
    async def test_api_is_accessible(self, async_client: AsyncClient):
        """Test that API is accessible."""
        response = await async_client.get("/api/v1/memos")
        assert response.status_code == 200

    @pytest.mark.asyncio
    async def test_cors_headers(self, async_client: AsyncClient):
        """Test CORS headers are present."""
        response = await async_client.options("/api/v1/memos")
        # CORS middleware should handle OPTIONS
        assert response.status_code in [200, 204, 405]
