"""Users API endpoints."""

from __future__ import annotations

from typing import TYPE_CHECKING
from uuid import UUID

from vikdata.models.role import (
    RoleResponse,
    UserRoleRequest,
    UserRoleResponse,
)

if TYPE_CHECKING:
    from vikdata.client import VikdataClient


class UsersAPI:
    """Users API endpoints.

    Handles user role assignments and permissions.
    """

    def __init__(self, client: "VikdataClient") -> None:
        """Initialize users API.

        Args:
            client: VikdataClient instance
        """
        self._client = client

    async def get_roles(self, user_id: UUID) -> list[RoleResponse]:
        """Get all roles assigned to a user.

        Args:
            user_id: User ID

        Returns:
            List of RoleResponse

        Raises:
            AuthenticationError: Not authenticated
            AuthorizationError: Missing 'users:read' permission
        """
        return await self._client.request(
            "GET",
            f"/api/v1/users/{user_id}/roles",
            response_model=list[RoleResponse],
        )

    async def assign_role(
        self,
        user_id: UUID,
        role_id: UUID,
    ) -> UserRoleResponse:
        """Assign a role to a user.

        Args:
            user_id: User ID
            role_id: Role ID to assign

        Returns:
            UserRoleResponse with assignment details

        Raises:
            AuthenticationError: Not authenticated
            AuthorizationError: Missing 'users:write' permission
            ResourceNotFoundError: User or role not found
        """
        request = UserRoleRequest(role_id=role_id)
        return await self._client.request(
            "POST",
            f"/api/v1/users/{user_id}/roles",
            json=request,
            response_model=UserRoleResponse,
        )

    async def remove_role(
        self,
        user_id: UUID,
        role_id: UUID,
    ) -> None:
        """Remove a role from a user.

        Args:
            user_id: User ID
            role_id: Role ID to remove

        Raises:
            AuthenticationError: Not authenticated
            AuthorizationError: Missing 'users:write' permission
        """
        await self._client.request(
            "DELETE",
            f"/api/v1/users/{user_id}/roles/{role_id}",
        )

    async def get_permissions(self, user_id: UUID) -> list[str]:
        """Get all effective permissions for a user (via their assigned roles).

        Args:
            user_id: User ID

        Returns:
            List of permission names (e.g., ['users:read', 'roles:write'])

        Raises:
            AuthenticationError: Not authenticated
            AuthorizationError: Missing 'users:read' permission
        """
        return await self._client.request(
            "GET",
            f"/api/v1/users/{user_id}/permissions",
            response_model=list[str],
        )
