"""Tests for user tools."""

import json
from unittest.mock import AsyncMock, MagicMock

import pytest

from platform_2step_mcp.tools.users import (
    USER_TOOLS,
    handle_user_tool,
)


class TestUserTools:
    """Tests for user tool definitions."""

    def test_user_tools_count(self):
        """Test that all user tools are defined."""
        assert len(USER_TOOLS) == 1

    def test_get_user_tool_defined(self):
        """Test get_user tool is properly defined."""
        tool = next((t for t in USER_TOOLS if t.name == "get_user"), None)
        assert tool is not None
        assert "user_id" in tool.inputSchema["required"]
        assert "company_id" in tool.inputSchema["required"]

    def test_get_user_tool_description(self):
        """Test get_user tool has proper description."""
        tool = next((t for t in USER_TOOLS if t.name == "get_user"), None)
        assert tool is not None
        assert "cross-company" in tool.description


class TestHandleUserTool:
    """Tests for handle_user_tool."""

    @pytest.fixture
    def mock_client(self):
        """Create a mock Platform2StepClient."""
        client = MagicMock()
        client.get_user = AsyncMock()
        return client

    async def test_get_user(self, mock_client):
        """Test get_user tool handler."""
        mock_client.get_user.return_value = {
            "id": 456,
            "email": "user@example.com",
            "first_name": "John",
            "last_name": "Doe",
        }

        result = await handle_user_tool(
            "get_user",
            {"user_id": 456, "company_id": 1238},
            mock_client,
        )

        assert len(result) == 1
        assert result[0].type == "text"
        data = json.loads(result[0].text)
        assert data["id"] == 456
        assert data["email"] == "user@example.com"
        assert data["first_name"] == "John"
        assert data["last_name"] == "Doe"
        mock_client.get_user.assert_called_once_with(
            user_id=456,
            company_id=1238,
        )

    async def test_unknown_tool_raises_error(self, mock_client):
        """Test that unknown tool raises ValueError."""
        with pytest.raises(ValueError, match="Unknown user tool"):
            await handle_user_tool(
                "unknown_tool",
                {},
                mock_client,
            )
