"""Tests for V2 SavedDisplaySettings API."""

import json

from pytest_httpx import HTTPXMock

from concentriq import ConcentriqClient
from concentriq.auth import ApiKeyAuth


class TestSavedDisplaySettingsList:
    """Tests for SavedDisplaySettings.list() behavior."""

    def test_list_returns_paginated_settings(self, httpx_mock: HTTPXMock):
        """List should return results and total from V2 response format."""
        httpx_mock.add_response(
            json={
                "results": [
                    {
                        "id": 1,
                        "name": "IF Settings 1",
                        "description": "Immunofluorescence preset",
                        "fluorescenceChannelsSettings": [
                            {
                                "channelName": "DAPI",
                                "color": "#0000FF",
                                "biomarker": "Nucleus",
                                "histogramMin": 0,
                                "histogramMax": 255,
                                "gamma": 1.0,
                            }
                        ],
                        "createdBy": 123,
                        "createdAt": "2024-01-01T00:00:00Z",
                        "lastUpdatedAt": "2024-01-01T00:00:00Z",
                    }
                ],
                "total": 1,
            },
        )

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

        assert len(result["results"]) == 1
        assert result["results"][0]["name"] == "IF Settings 1"
        assert len(result["results"][0]["fluorescenceChannelsSettings"]) == 1
        assert result["total"] == 1

        # Verify correct pagination params sent
        request = httpx_mock.get_request()
        pagination_param = request.url.params.get("pagination")
        parsed = json.loads(pagination_param)
        assert parsed["page"] == 0
        assert parsed["pageSize"] == 20
        assert parsed["orderBy"] == "id"
        assert parsed["orderDirection"] == "asc"


class TestSavedDisplaySettingsGet:
    """Tests for SavedDisplaySettings.get() behavior."""

    def test_get_returns_single_setting(self, httpx_mock: HTTPXMock):
        """Get should use plural path and return flat resource object."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/v2/savedImageDisplaySettingss/123",
            json={
                "id": 123,
                "name": "Test Settings",
                "description": "Test",
                "fluorescenceChannelsSettings": [
                    {"channelName": "FITC", "color": "#00FF00"}
                ],
                "createdBy": 456,
                "createdAt": "2024-01-01T00:00:00Z",
                "lastUpdatedAt": "2024-01-01T00:00:00Z",
            },
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v2.saved_display_settings.get(id=123)

        assert result["id"] == 123
        assert result["name"] == "Test Settings"


class TestSavedDisplaySettingsCreate:
    """Tests for SavedDisplaySettings.create() behavior."""

    def test_create_returns_created_setting(self, httpx_mock: HTTPXMock):
        """Create should return the newly created saved display setting."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/v2/savedImageDisplaySettingss",
            method="POST",
            status_code=201,
            json={
                "id": 789,
                "name": "New Settings",
                "description": "New preset",
                "fluorescenceChannelsSettings": [
                    {
                        "channelName": "Cy5",
                        "color": "#FF0000",
                        "histogramMin": 10,
                        "histogramMax": 200,
                    }
                ],
                "createdBy": 111,
                "createdAt": "2024-01-02T00:00:00Z",
                "lastUpdatedAt": "2024-01-02T00:00:00Z",
            },
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v2.saved_display_settings.create(
            {
                "name": "New Settings",
                "description": "New preset",
                "fluorescenceChannelsSettings": [
                    {
                        "channelName": "Cy5",
                        "color": "#FF0000",
                        "histogramMin": 10,
                        "histogramMax": 200,
                    }
                ],
            }
        )

        assert result["id"] == 789
        assert result["name"] == "New Settings"


class TestSavedDisplaySettingsUpdate:
    """Tests for SavedDisplaySettings.update() behavior."""

    def test_update_returns_updated_setting(self, httpx_mock: HTTPXMock):
        """Update should use plural path and return the updated setting."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/v2/savedImageDisplaySettingss/123",
            method="PATCH",
            json={
                "id": 123,
                "name": "Updated Settings",
                "description": "Updated",
                "fluorescenceChannelsSettings": [
                    {"channelName": "DAPI", "color": "#0000FF"}
                ],
                "createdBy": 456,
                "createdAt": "2024-01-01T00:00:00Z",
                "lastUpdatedAt": "2024-01-03T00:00:00Z",
            },
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v2.saved_display_settings.update(
            id=123, data={"name": "Updated Settings"}
        )

        assert result["id"] == 123
        assert result["name"] == "Updated Settings"


class TestSavedDisplaySettingsDelete:
    """Tests for SavedDisplaySettings.delete() behavior."""

    def test_delete_returns_success(self, httpx_mock: HTTPXMock):
        """Delete should use plural path and complete successfully."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/v2/savedImageDisplaySettingss/123",
            method="DELETE",
            status_code=204,
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v2.saved_display_settings.delete(id=123)

        assert result is None
