"""Tests for MetadataValues client."""

import pytest
from pytest_httpx import HTTPXMock

from concentriq import ConcentriqClient
from concentriq.auth import ApiKeyAuth
from concentriq.models.v1.filters import MetadataValueFilters


class TestMetadataValuesList:
    """Tests for MetadataValues.list() behavior."""

    def test_list_returns_list_of_values(self, httpx_mock: HTTPXMock):
        """List should return a list of metadata values."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/metadata-values",
            json={
                "meta": {"status": 200},
                "data": [
                    {"fieldId": 1, "resourceId": "img_100", "content": "Patient A"},
                    {"fieldId": 2, "resourceId": "img_100", "content": 42},
                ],
            },
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v1.metadata_values.list()

        assert isinstance(result, list)
        assert len(result) == 2
        assert result[0]["fieldId"] == 1
        assert result[0]["content"] == "Patient A"

    def test_list_with_filters(self, httpx_mock: HTTPXMock):
        """List should send filter parameters to API."""
        # Match base URL - complex filter encoding handled by backend
        httpx_mock.add_response(json={"meta": {"status": 200}, "data": []})

        filters = MetadataValueFilters(imageSetId=[1, 2, 3], imageId=[100])

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v1.metadata_values.list(filters=filters)

        assert isinstance(result, list)

    def test_list_returns_empty_list_when_no_results(self, httpx_mock: HTTPXMock):
        """List should return empty list when API returns no data."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/metadata-values",
            json={"meta": {"status": 200}, "data": []},
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v1.metadata_values.list()

        assert result == []

    def test_list_raises_authentication_error_when_unauthorized(
        self, httpx_mock: HTTPXMock
    ):
        """List should raise AuthenticationError when API returns 401."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/metadata-values",
            status_code=401,
            json={"error": "Unauthorized"},
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )

        from concentriq.exceptions import AuthenticationError

        with pytest.raises(AuthenticationError):
            client.v1.metadata_values.list()


class TestMetadataValuesUpdate:
    """Tests for MetadataValues.update() behavior."""

    def test_update_returns_successfully(self, httpx_mock: HTTPXMock):
        """Update should complete successfully with batch values."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/metadata-values",
            method="PATCH",
            json={"meta": {"status": 200}, "data": {}},
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v1.metadata_values.update(
            [
                {"fieldId": 1, "resourceId": "img_100", "content": "Updated Value"},
                {"fieldId": 2, "resourceId": "img_100", "content": 99},
            ]
        )

        assert result is None  # PATCH returns empty data object

    def test_update_raises_validation_error_on_invalid_data(
        self, httpx_mock: HTTPXMock
    ):
        """Update should raise ValidationError when data is invalid."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/metadata-values",
            method="PATCH",
            status_code=400,
            json={"error": "metadataValues must be a non-empty array"},
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )

        from concentriq.exceptions import ValidationError

        with pytest.raises(ValidationError):
            client.v1.metadata_values.update([])

    def test_update_raises_authentication_error_when_unauthorized(
        self, httpx_mock: HTTPXMock
    ):
        """Update should raise AuthenticationError when not authenticated."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/metadata-values",
            method="PATCH",
            status_code=401,
            json={"error": "Unauthorized"},
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )

        from concentriq.exceptions import AuthenticationError

        with pytest.raises(AuthenticationError):
            client.v1.metadata_values.update(
                [{"fieldId": 1, "resourceId": "img_100", "content": "test"}]
            )
