"""Tests for V2 Modules API."""

import json

from pytest_httpx import HTTPXMock

from concentriq import ConcentriqClient
from concentriq.auth import ApiKeyAuth


class TestModulesList:
    """Tests for Modules.list() behavior."""

    def test_list_returns_paginated_modules(self, httpx_mock: HTTPXMock):
        """List should return results and total from V2 response format."""
        httpx_mock.add_response(
            json={
                "results": [
                    {"id": 1, "name": "External Module 1", "isActive": True},
                    {"id": 2, "name": "External Module 2", "isActive": False},
                ],
                "total": 2,
            },
        )

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

        assert len(result["results"]) == 2
        assert result["results"][0]["name"] == "External Module 1"
        assert result["results"][0]["isActive"] is True
        assert result["total"] == 2

        # 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 TestModulesGet:
    """Tests for Modules.get() behavior."""

    def test_get_returns_single_module(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/modules/123",
            json={"id": 123, "name": "Test Module", "isActive": True},
        )

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

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


class TestModulesCreate:
    """Tests for Modules.create() behavior."""

    def test_create_returns_created_module(self, httpx_mock: HTTPXMock):
        """Create should return the newly created module."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/v2/modules",
            method="POST",
            status_code=201,
            json={"id": 456, "name": "New Module", "isActive": True},
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v2.modules.create({"name": "New Module", "isActive": True})

        assert result["id"] == 456
        assert result["name"] == "New Module"


class TestModulesUpdate:
    """Tests for Modules.update() behavior."""

    def test_update_returns_updated_module(self, httpx_mock: HTTPXMock):
        """Update should use plural path and return the updated module."""
        httpx_mock.add_response(
            url="https://test.concentriq.com/api/v2/modules/123",
            method="PATCH",
            json={"id": 123, "name": "Updated Module", "isActive": False},
        )

        client = ConcentriqClient(
            base_url="https://test.concentriq.com", auth=ApiKeyAuth("test-key")
        )
        result = client.v2.modules.update(id=123, data={"isActive": False})

        assert result["id"] == 123
        assert result["isActive"] is False


class TestModulesDelete:
    """Tests for Modules.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/modules/123",
            method="DELETE",
            status_code=204,
        )

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

        assert result is None
