"""UserGroups API client for V2."""

import json
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from concentriq.client import ConcentriqClient


class UserGroups:
    """Client for UserGroup resources (/api/v2/userGroups).

    User groups are collections of users within an organization.
    """

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

        Args:
            client: The ConcentriqClient instance
        """
        self._client = client
        self._base_path = "/api/v2/userGroups"

    def list(
        self,
        page: int = 0,
        page_size: int = 20,
        order_by: str = "id",
        order_direction: str = "asc",
        filters: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        """List user groups with pagination.

        Args:
            page: Page number (0-indexed, default: 0)
            page_size: Number of items per page (default: 20)
            order_by: Field to order by (default: "id")
            order_direction: Sort direction, "asc" or "desc" (default: "asc")
            filters: Filter criteria (e.g., {"organizationId": 10})

        Returns:
            Dictionary with "results" (list of user groups) and "total" count

        Raises:
            AuthenticationError: If not authenticated
        """
        pagination: dict[str, Any] = {
            "page": page,
            "pageSize": page_size,
            "orderBy": order_by,
            "orderDirection": order_direction,
        }
        if filters:
            pagination["filter"] = filters

        params = {"pagination": json.dumps(pagination)}
        response = self._client._request("GET", self._base_path, params=params)
        return response.json()

    def get(self, id: int) -> dict[str, Any]:
        """Get a single user group by ID.

        Args:
            id: User group ID

        Returns:
            User group data

        Raises:
            AuthenticationError: If not authenticated
            NotFoundError: If user group doesn't exist
        """
        response = self._client._request("GET", f"{self._base_path}/{id}")
        return response.json()

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

        Args:
            data: User group data
                - organizationId: Organization ID (required)
                - name: Group name (required)
                - description: Group description (optional)

        Returns:
            Created user group data

        Raises:
            AuthenticationError: If not authenticated
            ValidationError: If required fields are missing
            AuthorizationError: If user lacks canManageGroups permission

        Note:
            Requires canManageGroups permission.
        """
        response = self._client._request("POST", self._base_path, json=data)
        return response.json()

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

        Args:
            id: User group ID
            data: User group data to update

        Returns:
            Updated user group data

        Raises:
            AuthenticationError: If not authenticated
            NotFoundError: If user group doesn't exist
            AuthorizationError: If user lacks canManageGroups permission

        Note:
            Requires canManageGroups permission.
        """
        response = self._client._request("PATCH", f"{self._base_path}/{id}", json=data)
        return response.json()

    def delete(self, id: int) -> None:
        """Delete a user group.

        Args:
            id: User group ID

        Returns:
            None

        Raises:
            AuthenticationError: If not authenticated
            NotFoundError: If user group doesn't exist
            AuthorizationError: If user lacks canManageGroups permission

        Note:
            Requires canManageGroups permission.
        """
        self._client._request("DELETE", f"{self._base_path}/{id}")
