from http import HTTPStatus
from typing import Any, Optional, Union, cast
from uuid import UUID

import httpx

from ...client import AuthenticatedClient, Client
from ...models.create_saml_2_identity_provider_response_200 import CreateSaml2IdentityProviderResponse200
from ...models.error_response import ErrorResponse
from ...models.identity_provider_settings import IdentityProviderSettings
from ...types import UNSET, Response, Unset


def _get_kwargs(
    organization_uid: UUID,
    *,
    body: IdentityProviderSettings,
    x_request_id: Union[Unset, UUID] = UNSET,
    x_client_version: Union[Unset, str] = UNSET,
) -> dict[str, Any]:
    headers: dict[str, Any] = {}
    if not isinstance(x_request_id, Unset):
        headers["X-Request-id"] = x_request_id

    if not isinstance(x_client_version, Unset):
        headers["X-Client-Version"] = x_client_version

    _kwargs: dict[str, Any] = {
        "method": "post",
        "url": f"/organizations/{organization_uid}/identityProviders/saml2",
    }

    _kwargs["json"] = body.to_dict()

    headers["Content-Type"] = "application/json"

    _kwargs["headers"] = headers
    return _kwargs


def _parse_response(
    *, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Union[Any, CreateSaml2IdentityProviderResponse200, ErrorResponse]:
    if response.status_code == 200:
        response_200 = CreateSaml2IdentityProviderResponse200.from_dict(response.json())

        return response_200

    if response.status_code == 202:
        response_202 = cast(Any, None)
        return response_202

    response_default = ErrorResponse.from_dict(response.json())

    return response_default


def _build_response(
    *, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[Any, CreateSaml2IdentityProviderResponse200, ErrorResponse]]:
    return Response(
        status_code=HTTPStatus(response.status_code),
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(client=client, response=response),
    )


def sync_detailed(
    organization_uid: UUID,
    *,
    client: Union[AuthenticatedClient, Client],
    body: IdentityProviderSettings,
    x_request_id: Union[Unset, UUID] = UNSET,
    x_client_version: Union[Unset, str] = UNSET,
) -> Response[Union[Any, CreateSaml2IdentityProviderResponse200, ErrorResponse]]:
    r"""Create SAML2 Identity Provider

     Creates a new SAML2 identity provider.
    > Before you create a new SAML2 identity provider for a company you must generate a company portal
    URL.

    Args:
        organization_uid (UUID):
        x_request_id (Union[Unset, UUID]):
        x_client_version (Union[Unset, str]):
        body (IdentityProviderSettings):  Example: {'name': 'myadfs', 'displayName': 'Microsoft
            Entra ID Federation Services', 'template': 'ADFS', 'type': 'SAML2',
            'configurationValidationSucceeded': True, 'errorMessage': None, 'configuration':
            '<identityProvider>\n  <saml2 entityId="http://vac.myserver.com/Saml2/myadfs/"
            returnUrl="http://vac.myserver.com/Saml2/myadfs/">\n    <federations>\n      <add metadata
            Location="https://adfs.mydomain.com/federationmetadata/2007-06/federationmetadata.xml"\n
            allowUnsolicitedAuthnResponse="true" />\n    </federations>\n
            </saml2>\n</identityProvider>\n', 'rulesCount': 1, 'configurationCompleted': True,
            'enabled': True}.

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[Union[Any, CreateSaml2IdentityProviderResponse200, ErrorResponse]]
    """

    kwargs = _get_kwargs(
        organization_uid=organization_uid,
        body=body,
        x_request_id=x_request_id,
        x_client_version=x_client_version,
    )

    response = client.get_httpx_client().request(
        **kwargs,
    )

    return _build_response(client=client, response=response)


def sync(
    organization_uid: UUID,
    *,
    client: Union[AuthenticatedClient, Client],
    body: IdentityProviderSettings,
    x_request_id: Union[Unset, UUID] = UNSET,
    x_client_version: Union[Unset, str] = UNSET,
) -> Optional[Union[Any, CreateSaml2IdentityProviderResponse200, ErrorResponse]]:
    r"""Create SAML2 Identity Provider

     Creates a new SAML2 identity provider.
    > Before you create a new SAML2 identity provider for a company you must generate a company portal
    URL.

    Args:
        organization_uid (UUID):
        x_request_id (Union[Unset, UUID]):
        x_client_version (Union[Unset, str]):
        body (IdentityProviderSettings):  Example: {'name': 'myadfs', 'displayName': 'Microsoft
            Entra ID Federation Services', 'template': 'ADFS', 'type': 'SAML2',
            'configurationValidationSucceeded': True, 'errorMessage': None, 'configuration':
            '<identityProvider>\n  <saml2 entityId="http://vac.myserver.com/Saml2/myadfs/"
            returnUrl="http://vac.myserver.com/Saml2/myadfs/">\n    <federations>\n      <add metadata
            Location="https://adfs.mydomain.com/federationmetadata/2007-06/federationmetadata.xml"\n
            allowUnsolicitedAuthnResponse="true" />\n    </federations>\n
            </saml2>\n</identityProvider>\n', 'rulesCount': 1, 'configurationCompleted': True,
            'enabled': True}.

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Union[Any, CreateSaml2IdentityProviderResponse200, ErrorResponse]
    """

    return sync_detailed(
        organization_uid=organization_uid,
        client=client,
        body=body,
        x_request_id=x_request_id,
        x_client_version=x_client_version,
    ).parsed


async def asyncio_detailed(
    organization_uid: UUID,
    *,
    client: Union[AuthenticatedClient, Client],
    body: IdentityProviderSettings,
    x_request_id: Union[Unset, UUID] = UNSET,
    x_client_version: Union[Unset, str] = UNSET,
) -> Response[Union[Any, CreateSaml2IdentityProviderResponse200, ErrorResponse]]:
    r"""Create SAML2 Identity Provider

     Creates a new SAML2 identity provider.
    > Before you create a new SAML2 identity provider for a company you must generate a company portal
    URL.

    Args:
        organization_uid (UUID):
        x_request_id (Union[Unset, UUID]):
        x_client_version (Union[Unset, str]):
        body (IdentityProviderSettings):  Example: {'name': 'myadfs', 'displayName': 'Microsoft
            Entra ID Federation Services', 'template': 'ADFS', 'type': 'SAML2',
            'configurationValidationSucceeded': True, 'errorMessage': None, 'configuration':
            '<identityProvider>\n  <saml2 entityId="http://vac.myserver.com/Saml2/myadfs/"
            returnUrl="http://vac.myserver.com/Saml2/myadfs/">\n    <federations>\n      <add metadata
            Location="https://adfs.mydomain.com/federationmetadata/2007-06/federationmetadata.xml"\n
            allowUnsolicitedAuthnResponse="true" />\n    </federations>\n
            </saml2>\n</identityProvider>\n', 'rulesCount': 1, 'configurationCompleted': True,
            'enabled': True}.

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[Union[Any, CreateSaml2IdentityProviderResponse200, ErrorResponse]]
    """

    kwargs = _get_kwargs(
        organization_uid=organization_uid,
        body=body,
        x_request_id=x_request_id,
        x_client_version=x_client_version,
    )

    response = await client.get_async_httpx_client().request(**kwargs)

    return _build_response(client=client, response=response)


async def asyncio(
    organization_uid: UUID,
    *,
    client: Union[AuthenticatedClient, Client],
    body: IdentityProviderSettings,
    x_request_id: Union[Unset, UUID] = UNSET,
    x_client_version: Union[Unset, str] = UNSET,
) -> Optional[Union[Any, CreateSaml2IdentityProviderResponse200, ErrorResponse]]:
    r"""Create SAML2 Identity Provider

     Creates a new SAML2 identity provider.
    > Before you create a new SAML2 identity provider for a company you must generate a company portal
    URL.

    Args:
        organization_uid (UUID):
        x_request_id (Union[Unset, UUID]):
        x_client_version (Union[Unset, str]):
        body (IdentityProviderSettings):  Example: {'name': 'myadfs', 'displayName': 'Microsoft
            Entra ID Federation Services', 'template': 'ADFS', 'type': 'SAML2',
            'configurationValidationSucceeded': True, 'errorMessage': None, 'configuration':
            '<identityProvider>\n  <saml2 entityId="http://vac.myserver.com/Saml2/myadfs/"
            returnUrl="http://vac.myserver.com/Saml2/myadfs/">\n    <federations>\n      <add metadata
            Location="https://adfs.mydomain.com/federationmetadata/2007-06/federationmetadata.xml"\n
            allowUnsolicitedAuthnResponse="true" />\n    </federations>\n
            </saml2>\n</identityProvider>\n', 'rulesCount': 1, 'configurationCompleted': True,
            'enabled': True}.

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Union[Any, CreateSaml2IdentityProviderResponse200, ErrorResponse]
    """

    return (
        await asyncio_detailed(
            organization_uid=organization_uid,
            client=client,
            body=body,
            x_request_id=x_request_id,
            x_client_version=x_client_version,
        )
    ).parsed
