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

import typing
import urllib.parse
from json.decoder import JSONDecodeError

from ..common.types.resource_identifier import ResourceIdentifier
from ..common.types.resource_type import ResourceType
from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.jsonable_encoder import jsonable_encoder
from ..core.pydantic_utilities import pydantic_v1
from ..core.query_encoder import encode_query
from ..core.remove_none_from_dict import remove_none_from_dict
from ..core.request_options import RequestOptions
from .types.check_bulk_resources_authorization_response import CheckBulkResourcesAuthorizationResponse
from .types.check_resource_authorization_response import CheckResourceAuthorizationResponse
from .types.resource_list_page import ResourceListPage

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


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

    def check_resource_authorization_for_user(
        self,
        *,
        resource_identifier: ResourceIdentifier,
        user_email: str,
        disable_cache: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> CheckResourceAuthorizationResponse:
        """
        Admin endpoint to check whether the specified user is authorized to read the specified resource.

        Parameters
        ----------
        resource_identifier : ResourceIdentifier
            The resource identifier for which you want to check authorization.


        user_email : str
            The user email to check authorization for.


        disable_cache : typing.Optional[bool]
            If specified, Credal will bypass the permissions cache and check current permissions for this resource


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

        Returns
        -------
        CheckResourceAuthorizationResponse

        Examples
        --------
        from credal import ResourceIdentifier_ExternalResourceId
        from credal.client import CredalApi

        client = CredalApi(
            api_key="YOUR_API_KEY",
        )
        client.permissions_service.check_resource_authorization_for_user(
            resource_identifier=ResourceIdentifier_ExternalResourceId(
                external_resource_id="170NrBm0Do7gdzvr54UvyslPVWkQFOA0lgNycFmdZJQr",
                resource_type="GOOGLE_DRIVE_ITEM",
            ),
            user_email="john.smith@foo.com",
        )
        """
        _request: typing.Dict[str, typing.Any] = {"resourceIdentifier": resource_identifier, "userEmail": user_email}
        if disable_cache is not OMIT:
            _request["disableCache"] = disable_cache
        _response = self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/", "v0/permissions/checkResourceAuthorizationForUser"
            ),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(_request)
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(_request),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(CheckResourceAuthorizationResponse, _response.json())  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def check_bulk_resources_authorization_for_user(
        self,
        *,
        resource_identifiers: typing.Sequence[ResourceIdentifier],
        user_email: str,
        disable_cache: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> CheckBulkResourcesAuthorizationResponse:
        """
        Admin endpoint to check whether the specified user is authorized to read the specified set of resources.

        Parameters
        ----------
        resource_identifiers : typing.Sequence[ResourceIdentifier]
            The set of resource identifier for which you want to check authorization. Currently limited to 20 resources.


        user_email : str
            The user email to check authorization for.


        disable_cache : typing.Optional[bool]
            If specified, Credal will bypass the permissions cache and check current permissions for all resources specified.


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

        Returns
        -------
        CheckBulkResourcesAuthorizationResponse

        Examples
        --------
        from credal import ResourceIdentifier_ExternalResourceId
        from credal.client import CredalApi

        client = CredalApi(
            api_key="YOUR_API_KEY",
        )
        client.permissions_service.check_bulk_resources_authorization_for_user(
            resource_identifiers=[
                ResourceIdentifier_ExternalResourceId(
                    external_resource_id="170NrBm0Do7gdzvr54UvyslPVWkQFOA0lgNycFmdZJQr",
                    resource_type="GOOGLE_DRIVE_ITEM",
                ),
                ResourceIdentifier_ExternalResourceId(
                    external_resource_id="sfsdfvr54UvyslPVWkQFOA0dfsdfsdflgNycFmdZJQr",
                    resource_type="ZENDESK_TICKET",
                ),
            ],
            user_email="john.smith@foo.com",
        )
        """
        _request: typing.Dict[str, typing.Any] = {"resourceIdentifiers": resource_identifiers, "userEmail": user_email}
        if disable_cache is not OMIT:
            _request["disableCache"] = disable_cache
        _response = self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/", "v0/permissions/checkBulkResourcesAuthorizationForUser"
            ),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(_request)
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(_request),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(CheckBulkResourcesAuthorizationResponse, _response.json())  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def list_cached_authorized_resources_for_user(
        self,
        *,
        user_email: str,
        resource_type: typing.Optional[ResourceType] = OMIT,
        limit: typing.Optional[int] = OMIT,
        offset: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ResourceListPage:
        """
        Admin endpoint to list all resources that the specified user is authorized to read. Note this endpoint returns cached results and may not be up-to-date. You can use the checkResourceAuthorizationForUser endpoint with disableCache set to true to get the most up-to-date results.

        Parameters
        ----------
        user_email : str
            The user email to list authorized resources for.


        resource_type : typing.Optional[ResourceType]
            The type of resource you want to list. If not specified, all resource types will be listed.


        limit : typing.Optional[int]
            The maximum number of resources to return. Defaults to 100.


        offset : typing.Optional[int]
            The offset to use for pagination. If not specified, the first page of results will be returned.


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

        Returns
        -------
        ResourceListPage

        Examples
        --------
        from credal.client import CredalApi

        client = CredalApi(
            api_key="YOUR_API_KEY",
        )
        client.permissions_service.list_cached_authorized_resources_for_user(
            user_email="john.smith@foo.com",
        )
        """
        _request: typing.Dict[str, typing.Any] = {"userEmail": user_email}
        if resource_type is not OMIT:
            _request["resourceType"] = resource_type
        if limit is not OMIT:
            _request["limit"] = limit
        if offset is not OMIT:
            _request["offset"] = offset
        _response = self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/", "v0/permissions/listCachedAuthorizedResourcesForUser"
            ),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(_request)
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(_request),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(ResourceListPage, _response.json())  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


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

    async def check_resource_authorization_for_user(
        self,
        *,
        resource_identifier: ResourceIdentifier,
        user_email: str,
        disable_cache: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> CheckResourceAuthorizationResponse:
        """
        Admin endpoint to check whether the specified user is authorized to read the specified resource.

        Parameters
        ----------
        resource_identifier : ResourceIdentifier
            The resource identifier for which you want to check authorization.


        user_email : str
            The user email to check authorization for.


        disable_cache : typing.Optional[bool]
            If specified, Credal will bypass the permissions cache and check current permissions for this resource


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

        Returns
        -------
        CheckResourceAuthorizationResponse

        Examples
        --------
        from credal import ResourceIdentifier_ExternalResourceId
        from credal.client import AsyncCredalApi

        client = AsyncCredalApi(
            api_key="YOUR_API_KEY",
        )
        await client.permissions_service.check_resource_authorization_for_user(
            resource_identifier=ResourceIdentifier_ExternalResourceId(
                external_resource_id="170NrBm0Do7gdzvr54UvyslPVWkQFOA0lgNycFmdZJQr",
                resource_type="GOOGLE_DRIVE_ITEM",
            ),
            user_email="john.smith@foo.com",
        )
        """
        _request: typing.Dict[str, typing.Any] = {"resourceIdentifier": resource_identifier, "userEmail": user_email}
        if disable_cache is not OMIT:
            _request["disableCache"] = disable_cache
        _response = await self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/", "v0/permissions/checkResourceAuthorizationForUser"
            ),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(_request)
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(_request),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(CheckResourceAuthorizationResponse, _response.json())  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def check_bulk_resources_authorization_for_user(
        self,
        *,
        resource_identifiers: typing.Sequence[ResourceIdentifier],
        user_email: str,
        disable_cache: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> CheckBulkResourcesAuthorizationResponse:
        """
        Admin endpoint to check whether the specified user is authorized to read the specified set of resources.

        Parameters
        ----------
        resource_identifiers : typing.Sequence[ResourceIdentifier]
            The set of resource identifier for which you want to check authorization. Currently limited to 20 resources.


        user_email : str
            The user email to check authorization for.


        disable_cache : typing.Optional[bool]
            If specified, Credal will bypass the permissions cache and check current permissions for all resources specified.


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

        Returns
        -------
        CheckBulkResourcesAuthorizationResponse

        Examples
        --------
        from credal import ResourceIdentifier_ExternalResourceId
        from credal.client import AsyncCredalApi

        client = AsyncCredalApi(
            api_key="YOUR_API_KEY",
        )
        await client.permissions_service.check_bulk_resources_authorization_for_user(
            resource_identifiers=[
                ResourceIdentifier_ExternalResourceId(
                    external_resource_id="170NrBm0Do7gdzvr54UvyslPVWkQFOA0lgNycFmdZJQr",
                    resource_type="GOOGLE_DRIVE_ITEM",
                ),
                ResourceIdentifier_ExternalResourceId(
                    external_resource_id="sfsdfvr54UvyslPVWkQFOA0dfsdfsdflgNycFmdZJQr",
                    resource_type="ZENDESK_TICKET",
                ),
            ],
            user_email="john.smith@foo.com",
        )
        """
        _request: typing.Dict[str, typing.Any] = {"resourceIdentifiers": resource_identifiers, "userEmail": user_email}
        if disable_cache is not OMIT:
            _request["disableCache"] = disable_cache
        _response = await self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/", "v0/permissions/checkBulkResourcesAuthorizationForUser"
            ),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(_request)
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(_request),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(CheckBulkResourcesAuthorizationResponse, _response.json())  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def list_cached_authorized_resources_for_user(
        self,
        *,
        user_email: str,
        resource_type: typing.Optional[ResourceType] = OMIT,
        limit: typing.Optional[int] = OMIT,
        offset: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ResourceListPage:
        """
        Admin endpoint to list all resources that the specified user is authorized to read. Note this endpoint returns cached results and may not be up-to-date. You can use the checkResourceAuthorizationForUser endpoint with disableCache set to true to get the most up-to-date results.

        Parameters
        ----------
        user_email : str
            The user email to list authorized resources for.


        resource_type : typing.Optional[ResourceType]
            The type of resource you want to list. If not specified, all resource types will be listed.


        limit : typing.Optional[int]
            The maximum number of resources to return. Defaults to 100.


        offset : typing.Optional[int]
            The offset to use for pagination. If not specified, the first page of results will be returned.


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

        Returns
        -------
        ResourceListPage

        Examples
        --------
        from credal.client import AsyncCredalApi

        client = AsyncCredalApi(
            api_key="YOUR_API_KEY",
        )
        await client.permissions_service.list_cached_authorized_resources_for_user(
            user_email="john.smith@foo.com",
        )
        """
        _request: typing.Dict[str, typing.Any] = {"userEmail": user_email}
        if resource_type is not OMIT:
            _request["resourceType"] = resource_type
        if limit is not OMIT:
            _request["limit"] = limit
        if offset is not OMIT:
            _request["offset"] = offset
        _response = await self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/", "v0/permissions/listCachedAuthorizedResourcesForUser"
            ),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(_request)
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(_request),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(ResourceListPage, _response.json())  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)
