# 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 encode_path_param
from ...core.parse_error import ParsingError
from ...core.pydantic_utilities import parse_obj_as
from ...core.request_options import RequestOptions
from ...core.serialization import convert_and_respect_annotation_metadata
from ...errors.bad_request_error import BadRequestError
from ...errors.conflict_error import ConflictError
from ...errors.forbidden_error import ForbiddenError
from ...errors.too_many_requests_error import TooManyRequestsError
from ...errors.unauthorized_error import UnauthorizedError
from ...types.create_self_service_profile_sso_ticket_response_content import (
    CreateSelfServiceProfileSsoTicketResponseContent,
)
from ...types.self_service_profile_sso_ticket_connection_config import SelfServiceProfileSsoTicketConnectionConfig
from ...types.self_service_profile_sso_ticket_domain_aliases_config import (
    SelfServiceProfileSsoTicketDomainAliasesConfig,
)
from ...types.self_service_profile_sso_ticket_enabled_features import SelfServiceProfileSsoTicketEnabledFeatures
from ...types.self_service_profile_sso_ticket_enabled_organization import SelfServiceProfileSsoTicketEnabledOrganization
from ...types.self_service_profile_sso_ticket_provisioning_config import SelfServiceProfileSsoTicketProvisioningConfig
from ...types.third_party_client_access_config import ThirdPartyClientAccessConfig
from pydantic import ValidationError

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


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

    def create(
        self,
        id: str,
        *,
        connection_id: typing.Optional[str] = OMIT,
        connection_config: typing.Optional[SelfServiceProfileSsoTicketConnectionConfig] = OMIT,
        enabled_clients: typing.Optional[typing.Sequence[str]] = OMIT,
        enabled_organizations: typing.Optional[typing.Sequence[SelfServiceProfileSsoTicketEnabledOrganization]] = OMIT,
        ttl_sec: typing.Optional[int] = OMIT,
        domain_aliases_config: typing.Optional[SelfServiceProfileSsoTicketDomainAliasesConfig] = OMIT,
        provisioning_config: typing.Optional[SelfServiceProfileSsoTicketProvisioningConfig] = OMIT,
        use_for_organization_discovery: typing.Optional[bool] = OMIT,
        third_party_client_access_config: typing.Optional[ThirdPartyClientAccessConfig] = OMIT,
        enabled_features: typing.Optional[SelfServiceProfileSsoTicketEnabledFeatures] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[CreateSelfServiceProfileSsoTicketResponseContent]:
        """
        Creates an access ticket to initiate the Self-Service Enterprise Configuration flow using a self-service profile.

        Parameters
        ----------
        id : str
            The id of the self-service profile to retrieve

        connection_id : typing.Optional[str]
            If provided, this will allow editing of the provided connection during the Self-Service Enterprise Configuration flow

        connection_config : typing.Optional[SelfServiceProfileSsoTicketConnectionConfig]

        enabled_clients : typing.Optional[typing.Sequence[str]]
            List of client_ids that the connection will be enabled for.

        enabled_organizations : typing.Optional[typing.Sequence[SelfServiceProfileSsoTicketEnabledOrganization]]
            List of organizations that the connection will be enabled for.

        ttl_sec : typing.Optional[int]
            Number of seconds for which the ticket is valid before expiration. If unspecified or set to 0, this value defaults to 432000 seconds (5 days).

        domain_aliases_config : typing.Optional[SelfServiceProfileSsoTicketDomainAliasesConfig]

        provisioning_config : typing.Optional[SelfServiceProfileSsoTicketProvisioningConfig]

        use_for_organization_discovery : typing.Optional[bool]
            Indicates whether a verified domain should be used for organization discovery during authentication.

        third_party_client_access_config : typing.Optional[ThirdPartyClientAccessConfig]

        enabled_features : typing.Optional[SelfServiceProfileSsoTicketEnabledFeatures]

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

        Returns
        -------
        HttpResponse[CreateSelfServiceProfileSsoTicketResponseContent]
            Self-Service Enterprise Configuration Access Ticket successfully created.
        """
        _response = self._client_wrapper.httpx_client.request(
            f"self-service-profiles/{encode_path_param(id)}/sso-ticket",
            method="POST",
            json={
                "connection_id": connection_id,
                "connection_config": convert_and_respect_annotation_metadata(
                    object_=connection_config, annotation=SelfServiceProfileSsoTicketConnectionConfig, direction="write"
                ),
                "enabled_clients": enabled_clients,
                "enabled_organizations": convert_and_respect_annotation_metadata(
                    object_=enabled_organizations,
                    annotation=typing.Sequence[SelfServiceProfileSsoTicketEnabledOrganization],
                    direction="write",
                ),
                "ttl_sec": ttl_sec,
                "domain_aliases_config": convert_and_respect_annotation_metadata(
                    object_=domain_aliases_config,
                    annotation=SelfServiceProfileSsoTicketDomainAliasesConfig,
                    direction="write",
                ),
                "provisioning_config": convert_and_respect_annotation_metadata(
                    object_=provisioning_config,
                    annotation=SelfServiceProfileSsoTicketProvisioningConfig,
                    direction="write",
                ),
                "use_for_organization_discovery": use_for_organization_discovery,
                "third_party_client_access_config": convert_and_respect_annotation_metadata(
                    object_=third_party_client_access_config, annotation=ThirdPartyClientAccessConfig, direction="write"
                ),
                "enabled_features": convert_and_respect_annotation_metadata(
                    object_=enabled_features, annotation=SelfServiceProfileSsoTicketEnabledFeatures, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateSelfServiceProfileSsoTicketResponseContent,
                    parse_obj_as(
                        type_=CreateSelfServiceProfileSsoTicketResponseContent,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 409:
                raise ConflictError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def revoke(
        self, profile_id: str, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[None]:
        """
        Revokes a Self-Service Enterprise Configuration access ticket and invalidates associated sessions. The ticket will no longer be accepted to initiate a Self-Service Enterprise Configuration session. If any users have already started a session through this ticket, their session will be terminated. Clients should expect a `202 Accepted` response upon successful processing, indicating that the request has been acknowledged and that the revocation is underway but may not be fully completed at the time of response. If the specified ticket does not exist, a `202 Accepted` response is also returned, signaling that no further action is required.
        Clients should treat these `202` responses as an acknowledgment that the request has been accepted and is in progress, even if the ticket was not found.

        Parameters
        ----------
        profile_id : str
            The id of the self-service profile

        id : str
            The id of the ticket to revoke

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"self-service-profiles/{encode_path_param(profile_id)}/sso-ticket/{encode_path_param(id)}/revoke",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


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

    async def create(
        self,
        id: str,
        *,
        connection_id: typing.Optional[str] = OMIT,
        connection_config: typing.Optional[SelfServiceProfileSsoTicketConnectionConfig] = OMIT,
        enabled_clients: typing.Optional[typing.Sequence[str]] = OMIT,
        enabled_organizations: typing.Optional[typing.Sequence[SelfServiceProfileSsoTicketEnabledOrganization]] = OMIT,
        ttl_sec: typing.Optional[int] = OMIT,
        domain_aliases_config: typing.Optional[SelfServiceProfileSsoTicketDomainAliasesConfig] = OMIT,
        provisioning_config: typing.Optional[SelfServiceProfileSsoTicketProvisioningConfig] = OMIT,
        use_for_organization_discovery: typing.Optional[bool] = OMIT,
        third_party_client_access_config: typing.Optional[ThirdPartyClientAccessConfig] = OMIT,
        enabled_features: typing.Optional[SelfServiceProfileSsoTicketEnabledFeatures] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[CreateSelfServiceProfileSsoTicketResponseContent]:
        """
        Creates an access ticket to initiate the Self-Service Enterprise Configuration flow using a self-service profile.

        Parameters
        ----------
        id : str
            The id of the self-service profile to retrieve

        connection_id : typing.Optional[str]
            If provided, this will allow editing of the provided connection during the Self-Service Enterprise Configuration flow

        connection_config : typing.Optional[SelfServiceProfileSsoTicketConnectionConfig]

        enabled_clients : typing.Optional[typing.Sequence[str]]
            List of client_ids that the connection will be enabled for.

        enabled_organizations : typing.Optional[typing.Sequence[SelfServiceProfileSsoTicketEnabledOrganization]]
            List of organizations that the connection will be enabled for.

        ttl_sec : typing.Optional[int]
            Number of seconds for which the ticket is valid before expiration. If unspecified or set to 0, this value defaults to 432000 seconds (5 days).

        domain_aliases_config : typing.Optional[SelfServiceProfileSsoTicketDomainAliasesConfig]

        provisioning_config : typing.Optional[SelfServiceProfileSsoTicketProvisioningConfig]

        use_for_organization_discovery : typing.Optional[bool]
            Indicates whether a verified domain should be used for organization discovery during authentication.

        third_party_client_access_config : typing.Optional[ThirdPartyClientAccessConfig]

        enabled_features : typing.Optional[SelfServiceProfileSsoTicketEnabledFeatures]

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

        Returns
        -------
        AsyncHttpResponse[CreateSelfServiceProfileSsoTicketResponseContent]
            Self-Service Enterprise Configuration Access Ticket successfully created.
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"self-service-profiles/{encode_path_param(id)}/sso-ticket",
            method="POST",
            json={
                "connection_id": connection_id,
                "connection_config": convert_and_respect_annotation_metadata(
                    object_=connection_config, annotation=SelfServiceProfileSsoTicketConnectionConfig, direction="write"
                ),
                "enabled_clients": enabled_clients,
                "enabled_organizations": convert_and_respect_annotation_metadata(
                    object_=enabled_organizations,
                    annotation=typing.Sequence[SelfServiceProfileSsoTicketEnabledOrganization],
                    direction="write",
                ),
                "ttl_sec": ttl_sec,
                "domain_aliases_config": convert_and_respect_annotation_metadata(
                    object_=domain_aliases_config,
                    annotation=SelfServiceProfileSsoTicketDomainAliasesConfig,
                    direction="write",
                ),
                "provisioning_config": convert_and_respect_annotation_metadata(
                    object_=provisioning_config,
                    annotation=SelfServiceProfileSsoTicketProvisioningConfig,
                    direction="write",
                ),
                "use_for_organization_discovery": use_for_organization_discovery,
                "third_party_client_access_config": convert_and_respect_annotation_metadata(
                    object_=third_party_client_access_config, annotation=ThirdPartyClientAccessConfig, direction="write"
                ),
                "enabled_features": convert_and_respect_annotation_metadata(
                    object_=enabled_features, annotation=SelfServiceProfileSsoTicketEnabledFeatures, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateSelfServiceProfileSsoTicketResponseContent,
                    parse_obj_as(
                        type_=CreateSelfServiceProfileSsoTicketResponseContent,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 409:
                raise ConflictError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def revoke(
        self, profile_id: str, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[None]:
        """
        Revokes a Self-Service Enterprise Configuration access ticket and invalidates associated sessions. The ticket will no longer be accepted to initiate a Self-Service Enterprise Configuration session. If any users have already started a session through this ticket, their session will be terminated. Clients should expect a `202 Accepted` response upon successful processing, indicating that the request has been acknowledged and that the revocation is underway but may not be fully completed at the time of response. If the specified ticket does not exist, a `202 Accepted` response is also returned, signaling that no further action is required.
        Clients should treat these `202` responses as an acknowledgment that the request has been accepted and is in progress, even if the ticket was not found.

        Parameters
        ----------
        profile_id : str
            The id of the self-service profile

        id : str
            The id of the ticket to revoke

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"self-service-profiles/{encode_path_param(profile_id)}/sso-ticket/{encode_path_param(id)}/revoke",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
