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

import typing
from ..core.client_wrapper import SyncClientWrapper
from ..commons.types.entity_id_base import EntityIdBase
from ..commons.types.app_user_identifier import AppUserIdentifier
from ..commons.types.user_data import UserData
from ..core.request_options import RequestOptions
from ..commons.types.app_user_response import AppUserResponse
from ..core.serialization import convert_and_respect_annotation_metadata
from ..core.pydantic_utilities import parse_obj_as
from ..commons.errors.not_found_error import NotFoundError
from ..commons.types.error_message import ErrorMessage
from ..commons.errors.bad_request_error import BadRequestError
from ..commons.errors.server_error import ServerError
from json.decoder import JSONDecodeError
from ..core.api_error import ApiError
from ..core.jsonable_encoder import jsonable_encoder
from ..core.client_wrapper import AsyncClientWrapper

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


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

    def create_or_update(
        self,
        *,
        user_id: EntityIdBase,
        identifiers: typing.Sequence[AppUserIdentifier],
        data: typing.Dict[str, UserData],
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AppUserResponse:
        """
        Update a user or create it if it doesn't exist.

        Parameters
        ----------
        user_id : EntityIdBase
            ID that uniquely identifies this app user

        identifiers : typing.Sequence[AppUserIdentifier]
            Used to determine whether two users from different apps are the same

        data : typing.Dict[str, UserData]

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

        Returns
        -------
        AppUserResponse

        Examples
        --------
        from mavenagi import MavenAGI
        from mavenagi.commons import AppUserIdentifier, EntityIdBase, UserData

        client = MavenAGI(
            organization_id="YOUR_ORGANIZATION_ID",
            agent_id="YOUR_AGENT_ID",
            app_id="YOUR_APP_ID",
            app_secret="YOUR_APP_SECRET",
        )
        client.users.create_or_update(
            user_id=EntityIdBase(
                reference_id="user-0",
            ),
            identifiers=[
                AppUserIdentifier(
                    value="joe@myapp.com",
                    type="EMAIL",
                )
            ],
            data={
                "name": UserData(
                    value="Joe",
                    visibility="VISIBLE",
                )
            },
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/users",
            method="PUT",
            json={
                "userId": convert_and_respect_annotation_metadata(
                    object_=user_id, annotation=EntityIdBase, direction="write"
                ),
                "identifiers": convert_and_respect_annotation_metadata(
                    object_=identifiers, annotation=typing.Sequence[AppUserIdentifier], direction="write"
                ),
                "data": convert_and_respect_annotation_metadata(
                    object_=data, annotation=typing.Dict[str, UserData], direction="write"
                ),
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    AppUserResponse,
                    parse_obj_as(
                        type_=AppUserResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 500:
                raise ServerError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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 get(
        self,
        user_id: str,
        *,
        app_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AppUserResponse:
        """
        Get a user by its supplied ID

        Parameters
        ----------
        user_id : str
            The reference ID of the user to get. All other entity ID fields are inferred from the request.

        app_id : typing.Optional[str]
            The App ID of the user to get. If not provided the ID of the calling app will be used.

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

        Returns
        -------
        AppUserResponse

        Examples
        --------
        from mavenagi import MavenAGI

        client = MavenAGI(
            organization_id="YOUR_ORGANIZATION_ID",
            agent_id="YOUR_AGENT_ID",
            app_id="YOUR_APP_ID",
            app_secret="YOUR_APP_SECRET",
        )
        client.users.get(
            user_id="user-0",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/users/{jsonable_encoder(user_id)}",
            method="GET",
            params={
                "appId": app_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    AppUserResponse,
                    parse_obj_as(
                        type_=AppUserResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 500:
                raise ServerError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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 delete(
        self,
        user_id: str,
        *,
        app_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Deletes all identifiers and user data saved by the specified app.
        Does not modify data or identifiers saved by other apps.

        If this user is linked to a user from another app, it will not be unlinked. Unlinking of users is not yet supported.

        <Warning>This is a destructive operation and cannot be undone.</Warning>

        Parameters
        ----------
        user_id : str
            The reference ID of the user to delete. All other entity ID fields are inferred from the request.

        app_id : typing.Optional[str]
            The App ID of the user to delete. If not provided the ID of the calling app will be used.

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

        Returns
        -------
        None

        Examples
        --------
        from mavenagi import MavenAGI

        client = MavenAGI(
            organization_id="YOUR_ORGANIZATION_ID",
            agent_id="YOUR_AGENT_ID",
            app_id="YOUR_APP_ID",
            app_secret="YOUR_APP_SECRET",
        )
        client.users.delete(
            user_id="user-0",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/users/{jsonable_encoder(user_id)}",
            method="DELETE",
            params={
                "appId": app_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 500:
                raise ServerError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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 AsyncUsersClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def create_or_update(
        self,
        *,
        user_id: EntityIdBase,
        identifiers: typing.Sequence[AppUserIdentifier],
        data: typing.Dict[str, UserData],
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AppUserResponse:
        """
        Update a user or create it if it doesn't exist.

        Parameters
        ----------
        user_id : EntityIdBase
            ID that uniquely identifies this app user

        identifiers : typing.Sequence[AppUserIdentifier]
            Used to determine whether two users from different apps are the same

        data : typing.Dict[str, UserData]

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

        Returns
        -------
        AppUserResponse

        Examples
        --------
        import asyncio

        from mavenagi import AsyncMavenAGI
        from mavenagi.commons import AppUserIdentifier, EntityIdBase, UserData

        client = AsyncMavenAGI(
            organization_id="YOUR_ORGANIZATION_ID",
            agent_id="YOUR_AGENT_ID",
            app_id="YOUR_APP_ID",
            app_secret="YOUR_APP_SECRET",
        )


        async def main() -> None:
            await client.users.create_or_update(
                user_id=EntityIdBase(
                    reference_id="user-0",
                ),
                identifiers=[
                    AppUserIdentifier(
                        value="joe@myapp.com",
                        type="EMAIL",
                    )
                ],
                data={
                    "name": UserData(
                        value="Joe",
                        visibility="VISIBLE",
                    )
                },
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/users",
            method="PUT",
            json={
                "userId": convert_and_respect_annotation_metadata(
                    object_=user_id, annotation=EntityIdBase, direction="write"
                ),
                "identifiers": convert_and_respect_annotation_metadata(
                    object_=identifiers, annotation=typing.Sequence[AppUserIdentifier], direction="write"
                ),
                "data": convert_and_respect_annotation_metadata(
                    object_=data, annotation=typing.Dict[str, UserData], direction="write"
                ),
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    AppUserResponse,
                    parse_obj_as(
                        type_=AppUserResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 500:
                raise ServerError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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 get(
        self,
        user_id: str,
        *,
        app_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AppUserResponse:
        """
        Get a user by its supplied ID

        Parameters
        ----------
        user_id : str
            The reference ID of the user to get. All other entity ID fields are inferred from the request.

        app_id : typing.Optional[str]
            The App ID of the user to get. If not provided the ID of the calling app will be used.

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

        Returns
        -------
        AppUserResponse

        Examples
        --------
        import asyncio

        from mavenagi import AsyncMavenAGI

        client = AsyncMavenAGI(
            organization_id="YOUR_ORGANIZATION_ID",
            agent_id="YOUR_AGENT_ID",
            app_id="YOUR_APP_ID",
            app_secret="YOUR_APP_SECRET",
        )


        async def main() -> None:
            await client.users.get(
                user_id="user-0",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/users/{jsonable_encoder(user_id)}",
            method="GET",
            params={
                "appId": app_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    AppUserResponse,
                    parse_obj_as(
                        type_=AppUserResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 500:
                raise ServerError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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 delete(
        self,
        user_id: str,
        *,
        app_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Deletes all identifiers and user data saved by the specified app.
        Does not modify data or identifiers saved by other apps.

        If this user is linked to a user from another app, it will not be unlinked. Unlinking of users is not yet supported.

        <Warning>This is a destructive operation and cannot be undone.</Warning>

        Parameters
        ----------
        user_id : str
            The reference ID of the user to delete. All other entity ID fields are inferred from the request.

        app_id : typing.Optional[str]
            The App ID of the user to delete. If not provided the ID of the calling app will be used.

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

        Returns
        -------
        None

        Examples
        --------
        import asyncio

        from mavenagi import AsyncMavenAGI

        client = AsyncMavenAGI(
            organization_id="YOUR_ORGANIZATION_ID",
            agent_id="YOUR_AGENT_ID",
            app_id="YOUR_APP_ID",
            app_secret="YOUR_APP_SECRET",
        )


        async def main() -> None:
            await client.users.delete(
                user_id="user-0",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/users/{jsonable_encoder(user_id)}",
            method="DELETE",
            params={
                "appId": app_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 500:
                raise ServerError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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)
