"""Tests for Folders client."""

import pytest
from pytest_httpx import HTTPXMock

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


class TestFoldersList:
    """Tests for Folders.list() behavior."""

    def test_list_returns_list_of_folders(self, httpx_mock: HTTPXMock):
        """List should return a list of folder data."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/folders",
            json={
                "meta": {"status": 200},
                "data": {
                    "folders": [
                        {"id": 1, "label": "Folder 1", "imageSetId": 100},
                        {"id": 2, "label": "Folder 2", "imageSetId": 100},
                    ]
                },
            },
        )

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

        assert isinstance(result, list)
        assert len(result) == 2
        assert result[0]["id"] == 1
        assert result[1]["label"] == "Folder 2"

    def test_list_with_pagination_parameters(self, httpx_mock: HTTPXMock):
        """List should send pagination parameters to API."""
        # Match base URL - don't care about exact JSON encoding
        httpx_mock.add_response(
            json={"meta": {"status": 200}, "data": {"folders": []}}
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v1.folders.list(page=2, rows_per_page=50)

        assert isinstance(result, list)

    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": {"folders": []}}
        )

        filters = FolderFilters(imageSetId=[100], hasMetadata=True)

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v1.folders.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/folders",
            json={"meta": {"status": 200}, "data": {"folders": []}},
        )

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

        assert result == []

    def test_list_with_include_metadata(self, httpx_mock: HTTPXMock):
        """List should send includeMetadata param when requested."""
        httpx_mock.add_response(
            json={"meta": {"status": 200}, "data": {"folders": []}},
        )

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

        request = httpx_mock.get_request()
        assert request.url.params.get("includeMetadata") == "true"

    def test_list_returns_paginated_response_with_meta(self, httpx_mock: HTTPXMock):
        """List should return PaginatedResponse with accessible meta."""
        httpx_mock.add_response(
            json={
                "meta": {
                    "status": 200,
                    "pagination": {"page": 1, "rowsPerPage": 20, "total": 50},
                },
                "data": {
                    "folders": [
                        {"id": 1, "label": "Folder 1", "imageSetId": 100},
                    ]
                },
            },
        )

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

        assert len(result) == 1
        assert result.meta["pagination"]["total"] == 50

    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/folders",
            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.folders.list()


class TestFoldersGet:
    """Tests for Folders.get() behavior."""

    def test_get_returns_single_folder(self, httpx_mock: HTTPXMock):
        """Get should return a single folder by ID."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/folders/123",
            json={
                "meta": {"status": 200},
                "data": {
                    "id": 123,
                    "label": "Test Folder",
                    "imageSetId": 100,
                    "folderParentId": None,
                },
            },
        )

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

        assert result["id"] == 123
        assert result["label"] == "Test Folder"
        assert result["imageSetId"] == 100

    def test_get_raises_not_found_for_invalid_id(self, httpx_mock: HTTPXMock):
        """Get should raise NotFoundError for non-existent folder."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/folders/99999",
            status_code=404,
            json={"error": "Folder not found"},
        )

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

        from concentriq.exceptions import NotFoundError

        with pytest.raises(NotFoundError):
            client.v1.folders.get(99999)


class TestFoldersCreate:
    """Tests for Folders.create() behavior."""

    def test_create_returns_created_folder(self, httpx_mock: HTTPXMock):
        """Create should return the newly created folder data."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/folders",
            method="POST",
            json={
                "meta": {"status": 201},
                "data": {
                    "id": 456,
                    "rank": 0,
                },
            },
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v1.folders.create(
            {
                "label": "New Folder",
                "imageSetId": 100,
                "folderParentId": None,
                "hasMetadata": False,
            }
        )

        assert result["id"] == 456
        assert result["rank"] == 0

    def test_create_raises_validation_error_on_invalid_data(
        self, httpx_mock: HTTPXMock
    ):
        """Create should raise ValidationError when data is invalid."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/folders",
            method="POST",
            status_code=400,
            json={"error": "Label is required"},
        )

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

        from concentriq.exceptions import ValidationError

        with pytest.raises(ValidationError):
            client.v1.folders.create({})

    def test_create_raises_authentication_error_when_unauthorized(
        self, httpx_mock: HTTPXMock
    ):
        """Create should raise AuthenticationError when not authenticated."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/folders",
            method="POST",
            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.folders.create({"label": "Test"})


class TestFoldersUpdate:
    """Tests for Folders.update() behavior."""

    def test_update_returns_successfully(self, httpx_mock: HTTPXMock):
        """Update should complete successfully."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/folders/123",
            method="PATCH",
            json={
                "meta": {"status": 200},
                "data": {"success": "Folder 123 successfully updated."},
            },
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v1.folders.update(123, {"label": "Updated Folder Name"})

        # Backend returns success message, not the full folder object
        assert result is None

    def test_update_raises_not_found_for_invalid_id(self, httpx_mock: HTTPXMock):
        """Update should raise NotFoundError for non-existent folder."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/folders/99999",
            method="PATCH",
            status_code=404,
            json={"error": "Folder not found"},
        )

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

        from concentriq.exceptions import NotFoundError

        with pytest.raises(NotFoundError):
            client.v1.folders.update(99999, {"label": "Updated"})

    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/folders/123",
            method="PATCH",
            status_code=400,
            json={"error": "Invalid data"},
        )

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

        from concentriq.exceptions import ValidationError

        with pytest.raises(ValidationError):
            client.v1.folders.update(123, {"invalid": "data"})

    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/folders/123",
            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.folders.update(123, {"label": "Updated"})


class TestFoldersDelete:
    """Tests for Folders.delete() behavior."""

    def test_delete_returns_successfully(self, httpx_mock: HTTPXMock):
        """Delete should complete successfully for valid ID."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/folders/123",
            method="DELETE",
            status_code=204,
        )

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

        assert result is None

    def test_delete_raises_not_found_for_invalid_id(self, httpx_mock: HTTPXMock):
        """Delete should raise NotFoundError for non-existent folder."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/folders/99999",
            method="DELETE",
            status_code=404,
            json={"error": "Folder not found"},
        )

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

        from concentriq.exceptions import NotFoundError

        with pytest.raises(NotFoundError):
            client.v1.folders.delete(99999)

    def test_delete_raises_authentication_error_when_unauthorized(
        self, httpx_mock: HTTPXMock
    ):
        """Delete should raise AuthenticationError when not authenticated."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/folders/123",
            method="DELETE",
            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.folders.delete(123)
