"""Tests for community pattern database endpoints."""

from unittest.mock import patch


class TestGetPatterns:
    """Tests for GET /v1/patterns."""

    def test_get_patterns_success(self, client, auth_header):
        with patch("api.db.get_org_patterns") as mock_patterns, \
             patch("api.db.get_pattern_stats") as mock_stats:
            mock_patterns.return_value = [
                {
                    "id": "pat_1",
                    "exception_signature": {"exception_type": "TimeoutError"},
                    "fix_type": "async_wait",
                },
            ]
            mock_stats.return_value = {"total": 1, "by_type": {"async_wait": 1}}
            response = client.get("/v1/patterns", headers=auth_header)
            assert response.status_code == 200
            data = response.json()
            assert data["total"] == 1
            assert len(data["patterns"]) == 1
            assert "stats" in data

    def test_get_patterns_empty(self, client, auth_header):
        with patch("api.db.get_org_patterns") as mock_patterns, \
             patch("api.db.get_pattern_stats") as mock_stats:
            mock_patterns.return_value = []
            mock_stats.return_value = {"total": 0}
            response = client.get("/v1/patterns", headers=auth_header)
            assert response.status_code == 200
            assert response.json()["total"] == 0

    def test_get_patterns_unauthorized(self, client):
        response = client.get("/v1/patterns")
        assert response.status_code == 401


class TestContributePatterns:
    """Tests for POST /v1/patterns."""

    def test_contribute_patterns_success(self, client, auth_header):
        with patch("api.db.store_contributed_pattern") as mock_store:
            mock_store.return_value = None
            response = client.post(
                "/v1/patterns",
                json={
                    "patterns": [
                        {
                            "exception_signature": {
                                "exception_type": "TimeoutError",
                                "stack_signature": "test_foo::line_42",
                            },
                            "fix_type": "async_wait",
                            "fix_description": "Add await to async call",
                            "fix_diff_pattern": "- call()\n+ await call()",
                        },
                    ],
                },
                headers=auth_header,
            )
            assert response.status_code == 200
            data = response.json()
            assert data["received"] == 1
            assert data["accepted"] == 1
            assert data["rejected"] == 0

    def test_contribute_patterns_invalid(self, client, auth_header):
        response = client.post(
            "/v1/patterns",
            json={
                "patterns": [
                    {"invalid_field": "no required fields"},
                ],
            },
            headers=auth_header,
        )
        assert response.status_code == 200
        data = response.json()
        assert data["rejected"] == 1
        assert data["accepted"] == 0

    def test_contribute_patterns_unauthorized(self, client):
        response = client.post(
            "/v1/patterns",
            json={"patterns": []},
        )
        assert response.status_code == 401


class TestCommunityPatterns:
    """Tests for GET /v1/patterns/community."""

    def test_get_community_patterns(self, client, auth_header):
        with patch("api.db.get_community_patterns") as mock_patterns:
            mock_patterns.return_value = [
                {"id": "cpat_1", "fix_type": "concurrency", "success_rate": 0.85},
            ]
            response = client.get("/v1/patterns/community", headers=auth_header)
            assert response.status_code == 200
            data = response.json()
            assert data["total"] == 1

    def test_get_community_patterns_unauthorized(self, client):
        response = client.get("/v1/patterns/community")
        assert response.status_code == 401
