# This file was auto-generated by Fern from our API Definition.

import typing
from json.decoder import JSONDecodeError

from ...core.api_error import ApiError
from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ...core.http_response import AsyncHttpResponse, HttpResponse
from ...core.jsonable_encoder import jsonable_encoder
from ...core.request_options import RequestOptions
from ...core.unchecked_base_model import construct_type
from ...errors.unprocessable_entity_error import UnprocessableEntityError
from ...types.resource_metadata_response_model import ResourceMetadataResponseModel
from ...types.workspace_resource_type import WorkspaceResourceType
from .types.body_share_workspace_resource_v_1_workspace_resources_resource_id_share_post_role import (
    BodyShareWorkspaceResourceV1WorkspaceResourcesResourceIdSharePostRole,
)

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class RawResourcesClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def get(
        self,
        resource_id: str,
        *,
        resource_type: WorkspaceResourceType,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ResourceMetadataResponseModel]:
        """
        Gets the metadata of a resource by ID.

        Parameters
        ----------
        resource_id : str
            The ID of the target resource.

        resource_type : WorkspaceResourceType
            Resource type of the target resource.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ResourceMetadataResponseModel]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/workspace/resources/{jsonable_encoder(resource_id)}",
            method="GET",
            params={
                "resource_type": resource_type,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ResourceMetadataResponseModel,
                    construct_type(
                        type_=ResourceMetadataResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def share(
        self,
        resource_id: str,
        *,
        role: BodyShareWorkspaceResourceV1WorkspaceResourcesResourceIdSharePostRole,
        resource_type: WorkspaceResourceType,
        user_email: typing.Optional[str] = OMIT,
        group_id: typing.Optional[str] = OMIT,
        workspace_api_key_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.Any]:
        """
        Grants a role (one of 'admin', 'editor', 'commenter', or 'viewer') on a workspace resource to a user, group, or workspace (service account) API key. This overrides any existing role the target has on the resource. To target a user or service account, pass only the user email; the user must be in your workspace. To target a group, pass only the group id. To target a workspace (service account) API key, pass the api key id; the resource will be shared with the service account associated with that key. You must have admin access to the resource to share it.

        Parameters
        ----------
        resource_id : str
            The ID of the target resource.

        role : BodyShareWorkspaceResourceV1WorkspaceResourcesResourceIdSharePostRole
            Role to grant to the target: one of 'admin', 'editor', 'commenter', or 'viewer'.

        resource_type : WorkspaceResourceType
            Resource type of the target resource.

        user_email : typing.Optional[str]
            The email of the user or service account.

        group_id : typing.Optional[str]
            The ID of the target group. Use 'default' to set the resource's baseline role — every workspace member receives this role unless they hold a higher one through a direct user grant, group membership, or workspace (service account) API key.

        workspace_api_key_id : typing.Optional[str]
            The ID of the target workspace (service account) API key. This is not the API key string itself that you pass in the header for authentication — it is the key's ID, which workspace admins can find under Developers → Service Accounts.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[typing.Any]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/workspace/resources/{jsonable_encoder(resource_id)}/share",
            method="POST",
            json={
                "role": role,
                "resource_type": resource_type,
                "user_email": user_email,
                "group_id": group_id,
                "workspace_api_key_id": workspace_api_key_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if _response is None or not _response.text.strip():
                return HttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Any,
                    construct_type(
                        type_=typing.Any,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def unshare(
        self,
        resource_id: str,
        *,
        resource_type: WorkspaceResourceType,
        user_email: typing.Optional[str] = OMIT,
        group_id: typing.Optional[str] = OMIT,
        workspace_api_key_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.Any]:
        """
        Removes any existing role on a workspace resource from a user, group, or workspace (service account) API key. To target a user or service account, pass only the user email; the user must be in your workspace. To target a group, pass only the group id. To target a workspace (service account) API key, pass the api key id; the resource will be unshared from the service account associated with that key. You must have admin access to the resource to unshare it. You cannot remove permissions from the user who created the resource.

        Parameters
        ----------
        resource_id : str
            The ID of the target resource.

        resource_type : WorkspaceResourceType
            Resource type of the target resource.

        user_email : typing.Optional[str]
            The email of the user or service account.

        group_id : typing.Optional[str]
            The ID of the target group. Use 'default' to set the resource's baseline role — every workspace member receives this role unless they hold a higher one through a direct user grant, group membership, or workspace (service account) API key.

        workspace_api_key_id : typing.Optional[str]
            The ID of the target workspace (service account) API key. This is not the API key string itself that you pass in the header for authentication — it is the key's ID, which workspace admins can find under Developers → Service Accounts.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[typing.Any]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/workspace/resources/{jsonable_encoder(resource_id)}/unshare",
            method="POST",
            json={
                "resource_type": resource_type,
                "user_email": user_email,
                "group_id": group_id,
                "workspace_api_key_id": workspace_api_key_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if _response is None or not _response.text.strip():
                return HttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Any,
                    construct_type(
                        type_=typing.Any,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawResourcesClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def get(
        self,
        resource_id: str,
        *,
        resource_type: WorkspaceResourceType,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ResourceMetadataResponseModel]:
        """
        Gets the metadata of a resource by ID.

        Parameters
        ----------
        resource_id : str
            The ID of the target resource.

        resource_type : WorkspaceResourceType
            Resource type of the target resource.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ResourceMetadataResponseModel]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/workspace/resources/{jsonable_encoder(resource_id)}",
            method="GET",
            params={
                "resource_type": resource_type,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ResourceMetadataResponseModel,
                    construct_type(
                        type_=ResourceMetadataResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def share(
        self,
        resource_id: str,
        *,
        role: BodyShareWorkspaceResourceV1WorkspaceResourcesResourceIdSharePostRole,
        resource_type: WorkspaceResourceType,
        user_email: typing.Optional[str] = OMIT,
        group_id: typing.Optional[str] = OMIT,
        workspace_api_key_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.Any]:
        """
        Grants a role (one of 'admin', 'editor', 'commenter', or 'viewer') on a workspace resource to a user, group, or workspace (service account) API key. This overrides any existing role the target has on the resource. To target a user or service account, pass only the user email; the user must be in your workspace. To target a group, pass only the group id. To target a workspace (service account) API key, pass the api key id; the resource will be shared with the service account associated with that key. You must have admin access to the resource to share it.

        Parameters
        ----------
        resource_id : str
            The ID of the target resource.

        role : BodyShareWorkspaceResourceV1WorkspaceResourcesResourceIdSharePostRole
            Role to grant to the target: one of 'admin', 'editor', 'commenter', or 'viewer'.

        resource_type : WorkspaceResourceType
            Resource type of the target resource.

        user_email : typing.Optional[str]
            The email of the user or service account.

        group_id : typing.Optional[str]
            The ID of the target group. Use 'default' to set the resource's baseline role — every workspace member receives this role unless they hold a higher one through a direct user grant, group membership, or workspace (service account) API key.

        workspace_api_key_id : typing.Optional[str]
            The ID of the target workspace (service account) API key. This is not the API key string itself that you pass in the header for authentication — it is the key's ID, which workspace admins can find under Developers → Service Accounts.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[typing.Any]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/workspace/resources/{jsonable_encoder(resource_id)}/share",
            method="POST",
            json={
                "role": role,
                "resource_type": resource_type,
                "user_email": user_email,
                "group_id": group_id,
                "workspace_api_key_id": workspace_api_key_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if _response is None or not _response.text.strip():
                return AsyncHttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Any,
                    construct_type(
                        type_=typing.Any,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def unshare(
        self,
        resource_id: str,
        *,
        resource_type: WorkspaceResourceType,
        user_email: typing.Optional[str] = OMIT,
        group_id: typing.Optional[str] = OMIT,
        workspace_api_key_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.Any]:
        """
        Removes any existing role on a workspace resource from a user, group, or workspace (service account) API key. To target a user or service account, pass only the user email; the user must be in your workspace. To target a group, pass only the group id. To target a workspace (service account) API key, pass the api key id; the resource will be unshared from the service account associated with that key. You must have admin access to the resource to unshare it. You cannot remove permissions from the user who created the resource.

        Parameters
        ----------
        resource_id : str
            The ID of the target resource.

        resource_type : WorkspaceResourceType
            Resource type of the target resource.

        user_email : typing.Optional[str]
            The email of the user or service account.

        group_id : typing.Optional[str]
            The ID of the target group. Use 'default' to set the resource's baseline role — every workspace member receives this role unless they hold a higher one through a direct user grant, group membership, or workspace (service account) API key.

        workspace_api_key_id : typing.Optional[str]
            The ID of the target workspace (service account) API key. This is not the API key string itself that you pass in the header for authentication — it is the key's ID, which workspace admins can find under Developers → Service Accounts.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[typing.Any]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/workspace/resources/{jsonable_encoder(resource_id)}/unshare",
            method="POST",
            json={
                "resource_type": resource_type,
                "user_email": user_email,
                "group_id": group_id,
                "workspace_api_key_id": workspace_api_key_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if _response is None or not _response.text.strip():
                return AsyncHttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Any,
                    construct_type(
                        type_=typing.Any,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
