"""User tools: tms_search_users."""
from __future__ import annotations

import json

from api_client import ApiError, client


def register(mcp):
    @mcp.tool()
    async def tms_search_users(query: str, organization_id: int | None = None) -> str:
        """Search for users by name or email. Minimum 2 characters required.

        Args:
            query: Search string (matches against name and email, min 2 chars).
            organization_id: Optionally scope the search to members of a specific organization.
        """
        try:
            data = await client.get(
                "/auth/users/search", q=query, organization_id=organization_id
            )
            if not data:
                return f"No users found matching '{query}'."
            return json.dumps(data, indent=2, default=str)
        except ApiError as e:
            return str(e)
