"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""

from .basesdk import BaseSDK
from kombo import errors, models, utils
from kombo._hooks import HookContext
from kombo.types import OptionalNullable, UNSET
from kombo.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, Mapping, Optional


class Connect(BaseSDK):
    def create_connection_link(
        self,
        *,
        end_user_email: str,
        end_user_organization_name: str,
        end_user_origin_id: OptionalNullable[str] = UNSET,
        remote_environment: OptionalNullable[str] = UNSET,
        integration_category: Optional[
            models.PostConnectCreateLinkRequestBodyIntegrationCategory
        ] = "HRIS",
        integration_tool: OptionalNullable[models.IntegrationTool] = UNSET,
        language: OptionalNullable[
            models.PostConnectCreateLinkRequestBodyLanguage
        ] = "en",
        scope_config_id: OptionalNullable[str] = UNSET,
        enable_filtering: Optional[bool] = False,
        enable_field_mapping: Optional[bool] = False,
        link_type: Optional[
            models.PostConnectCreateLinkRequestBodyLinkType
        ] = "EMBEDDED",
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.PostConnectCreateLinkPositiveResponse:
        r"""Create connection link

        Generate a unique link that allows your user to enter the embedded Kombo Connect flow.

        > Check out [our full guide](/connect/embedded-flow) for more details about implementing the connection flow into your app.

        > Kombo will not deduplicate integrations for you that are created with this endpoint. You are responsible for keeping track of integrations in your system and prevent customers from connecting the same tool again. Use the [reconnection link](/v1/post-integrations-integration-id-relink) endpoint if you want a customer to update their credentials.

        ### Example Request Body

        ```json
        {
        \"end_user_email\": \"test@example.com\",
        \"end_user_organization_name\": \"Test Inc.\",
        \"integration_category\": \"HRIS\",
        \"integration_tool\": \"personio\",
        \"end_user_origin_id\": \"123\",
        \"language\": \"en\",
        \"link_type\": \"EMBEDDED\"
        }
        ```

        :param end_user_email: The email of the user this link is meant for.
        :param end_user_organization_name: The name of the user's organization.
        :param end_user_origin_id: The id the user/organization has in your own database.
        :param remote_environment: If the tool you want to connect offers different environments, you can specify which one you want to connect to here. If you don't specify this, we'll assume you want to use the production environment. Note that this can only be used if you've also specified a tool through `integration_tool`.
        :param integration_category: Category of the integration you want your customer to create.
        :param integration_tool: Pre-define a tool this integration link can be used for.
        :param language: Language of the connection flow UI.
        :param scope_config_id: Specify a scope config that should be used for this integration. This is an advanced feature, only use it if you know what you're doing!
        :param enable_filtering: Enable the [filtering feature](https://docs.kombo.dev/other/filtering) for the integration. HRIS only.
        :param enable_field_mapping: Enable the [field mapping feature](https://docs.kombo.dev/hris/features/setup-flow/introduction#field-mapping) for this integration.
        :param link_type: The type of link you want to create. `EMBEDDED` is for the [embedded flow](../guides/connect/embedded-flow) using the Kombo Connect SDK (these links are valid for 1 hour) and `MAGIC_LINK` is for [magic links](../guides/connect/magic-links) which you send out manually to customers (there are valid for 1 year).

            This defaults to `EMBEDDED`, which is our recommended method of implementing the connection flow for a seamless user experience.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.PostConnectCreateLinkRequestBody(
            end_user_email=end_user_email,
            end_user_organization_name=end_user_organization_name,
            end_user_origin_id=end_user_origin_id,
            remote_environment=remote_environment,
            integration_category=integration_category,
            integration_tool=integration_tool,
            language=language,
            scope_config_id=scope_config_id,
            enable_filtering=enable_filtering,
            enable_field_mapping=enable_field_mapping,
            link_type=link_type,
        )

        req = self._build_request(
            method="POST",
            path="/connect/create-link",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request, False, False, "json", models.PostConnectCreateLinkRequestBody
            ),
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="PostConnectCreateLink",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["default"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(
                models.PostConnectCreateLinkPositiveResponse, http_res
            )
        if utils.match_response(http_res, "default", "application/json"):
            response_data = unmarshal_json_response(
                errors.KomboGeneralErrorData, http_res
            )
            raise errors.KomboGeneralError(response_data, http_res)

        raise errors.SDKDefaultError("Unexpected response received", http_res)

    async def create_connection_link_async(
        self,
        *,
        end_user_email: str,
        end_user_organization_name: str,
        end_user_origin_id: OptionalNullable[str] = UNSET,
        remote_environment: OptionalNullable[str] = UNSET,
        integration_category: Optional[
            models.PostConnectCreateLinkRequestBodyIntegrationCategory
        ] = "HRIS",
        integration_tool: OptionalNullable[models.IntegrationTool] = UNSET,
        language: OptionalNullable[
            models.PostConnectCreateLinkRequestBodyLanguage
        ] = "en",
        scope_config_id: OptionalNullable[str] = UNSET,
        enable_filtering: Optional[bool] = False,
        enable_field_mapping: Optional[bool] = False,
        link_type: Optional[
            models.PostConnectCreateLinkRequestBodyLinkType
        ] = "EMBEDDED",
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.PostConnectCreateLinkPositiveResponse:
        r"""Create connection link

        Generate a unique link that allows your user to enter the embedded Kombo Connect flow.

        > Check out [our full guide](/connect/embedded-flow) for more details about implementing the connection flow into your app.

        > Kombo will not deduplicate integrations for you that are created with this endpoint. You are responsible for keeping track of integrations in your system and prevent customers from connecting the same tool again. Use the [reconnection link](/v1/post-integrations-integration-id-relink) endpoint if you want a customer to update their credentials.

        ### Example Request Body

        ```json
        {
        \"end_user_email\": \"test@example.com\",
        \"end_user_organization_name\": \"Test Inc.\",
        \"integration_category\": \"HRIS\",
        \"integration_tool\": \"personio\",
        \"end_user_origin_id\": \"123\",
        \"language\": \"en\",
        \"link_type\": \"EMBEDDED\"
        }
        ```

        :param end_user_email: The email of the user this link is meant for.
        :param end_user_organization_name: The name of the user's organization.
        :param end_user_origin_id: The id the user/organization has in your own database.
        :param remote_environment: If the tool you want to connect offers different environments, you can specify which one you want to connect to here. If you don't specify this, we'll assume you want to use the production environment. Note that this can only be used if you've also specified a tool through `integration_tool`.
        :param integration_category: Category of the integration you want your customer to create.
        :param integration_tool: Pre-define a tool this integration link can be used for.
        :param language: Language of the connection flow UI.
        :param scope_config_id: Specify a scope config that should be used for this integration. This is an advanced feature, only use it if you know what you're doing!
        :param enable_filtering: Enable the [filtering feature](https://docs.kombo.dev/other/filtering) for the integration. HRIS only.
        :param enable_field_mapping: Enable the [field mapping feature](https://docs.kombo.dev/hris/features/setup-flow/introduction#field-mapping) for this integration.
        :param link_type: The type of link you want to create. `EMBEDDED` is for the [embedded flow](../guides/connect/embedded-flow) using the Kombo Connect SDK (these links are valid for 1 hour) and `MAGIC_LINK` is for [magic links](../guides/connect/magic-links) which you send out manually to customers (there are valid for 1 year).

            This defaults to `EMBEDDED`, which is our recommended method of implementing the connection flow for a seamless user experience.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.PostConnectCreateLinkRequestBody(
            end_user_email=end_user_email,
            end_user_organization_name=end_user_organization_name,
            end_user_origin_id=end_user_origin_id,
            remote_environment=remote_environment,
            integration_category=integration_category,
            integration_tool=integration_tool,
            language=language,
            scope_config_id=scope_config_id,
            enable_filtering=enable_filtering,
            enable_field_mapping=enable_field_mapping,
            link_type=link_type,
        )

        req = self._build_request_async(
            method="POST",
            path="/connect/create-link",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request, False, False, "json", models.PostConnectCreateLinkRequestBody
            ),
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="PostConnectCreateLink",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["default"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(
                models.PostConnectCreateLinkPositiveResponse, http_res
            )
        if utils.match_response(http_res, "default", "application/json"):
            response_data = unmarshal_json_response(
                errors.KomboGeneralErrorData, http_res
            )
            raise errors.KomboGeneralError(response_data, http_res)

        raise errors.SDKDefaultError("Unexpected response received", http_res)

    def get_integration_by_token(
        self,
        *,
        token: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.GetConnectIntegrationByTokenTokenPositiveResponse:
        r"""Get integration by token

        Use this endpoint with the token you get from the connection flow to retrieve information about the created integration.

        It works in a similar way as the OAuth2 code flow to securely retrieve information and connect the integration to your user.

        > Check out [our full guide](/connect/embedded-flow) for more details about implementing the connection flow into your app.

        This endpoint is used to ensure users can't trick your system connecting their
        account in your system to another customers integration. You don't get the integration ID
        from the `showKomboConnect(link)` function but only the short lived token used
        for this endpoint so that users can't send you arbitrary data that you would put
        into your system.

        :param token: GET /connect/integration-by-token/:token Parameter
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.GetConnectIntegrationByTokenTokenRequest(
            token=token,
        )

        req = self._build_request(
            method="GET",
            path="/connect/integration-by-token/{token}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="GetConnectIntegrationByTokenToken",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["default"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(
                models.GetConnectIntegrationByTokenTokenPositiveResponse, http_res
            )
        if utils.match_response(http_res, "default", "application/json"):
            response_data = unmarshal_json_response(
                errors.KomboGeneralErrorData, http_res
            )
            raise errors.KomboGeneralError(response_data, http_res)

        raise errors.SDKDefaultError("Unexpected response received", http_res)

    async def get_integration_by_token_async(
        self,
        *,
        token: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.GetConnectIntegrationByTokenTokenPositiveResponse:
        r"""Get integration by token

        Use this endpoint with the token you get from the connection flow to retrieve information about the created integration.

        It works in a similar way as the OAuth2 code flow to securely retrieve information and connect the integration to your user.

        > Check out [our full guide](/connect/embedded-flow) for more details about implementing the connection flow into your app.

        This endpoint is used to ensure users can't trick your system connecting their
        account in your system to another customers integration. You don't get the integration ID
        from the `showKomboConnect(link)` function but only the short lived token used
        for this endpoint so that users can't send you arbitrary data that you would put
        into your system.

        :param token: GET /connect/integration-by-token/:token Parameter
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.GetConnectIntegrationByTokenTokenRequest(
            token=token,
        )

        req = self._build_request_async(
            method="GET",
            path="/connect/integration-by-token/{token}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="GetConnectIntegrationByTokenToken",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["default"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(
                models.GetConnectIntegrationByTokenTokenPositiveResponse, http_res
            )
        if utils.match_response(http_res, "default", "application/json"):
            response_data = unmarshal_json_response(
                errors.KomboGeneralErrorData, http_res
            )
            raise errors.KomboGeneralError(response_data, http_res)

        raise errors.SDKDefaultError("Unexpected response received", http_res)
