"""Users resource client for V1."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from concentriq.client import ConcentriqClient


class Users:
    """Client for User resources (/api/users)."""

    def __init__(self, client: "ConcentriqClient"):
        """Initialize with client instance.

        Args:
            client: ConcentriqClient instance
        """
        self._client = client
        self._base_path = "/api/users"

    def list(self) -> list[dict[str, Any]]:
        """List all users.

        Returns:
            List of user dictionaries

        Raises:
            AuthenticationError: If not authenticated

        Example:
            users = client.v1.users.list()
            for user in users:
                print(f"{user['name']}: {user['email']}")
        """
        response = self._client._request("GET", self._base_path)
        data = response.json()

        # V1 API returns data in envelope format with 'users' key
        return data.get("data", {}).get("users", [])

    def create(self, data: dict[str, Any]) -> dict[str, Any]:
        """Create a new user.

        Args:
            data: User data (name, email, organizationId, sendEmail, forcePasswordChange, etc.)

        Returns:
            Created user dictionary with userId and temporary password

        Raises:
            AuthenticationError: If not authenticated
            ValidationError: If data is invalid

        Example:
            user = client.v1.users.create({
                "name": "John Doe",
                "email": "john@example.com",
                "organizationId": 1,
                "sendEmail": True
            })
            print(f"Created user {user['userId']} with password: {user['password']}")
        """
        response = self._client._request("POST", self._base_path, json=data)
        result = response.json()

        # V1 API returns data in envelope format
        return result.get("data", {})

    def update(self, id: int, data: dict[str, Any]) -> None:
        """Update an existing user.

        Args:
            id: User ID
            data: Updated user data (name, roleId, groupIds, isDisabled, defaultAnnotationColor, etc.)

        Returns:
            None (backend returns success message)

        Raises:
            AuthenticationError: If not authenticated
            NotFoundError: If user not found
            ValidationError: If data is invalid

        Example:
            client.v1.users.update(123, {
                "name": "Jane Doe Updated",
                "roleId": 5,
                "isDisabled": False
            })
        """
        self._client._request("PATCH", f"{self._base_path}/{id}", json=data)
        # PATCH returns success message, no need to return anything
