"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
# @generated-id: 0040e1e52add

from .basesdk import BaseSDK
from mollie import models, utils
from mollie._hooks import HookContext
from mollie.types import OptionalNullable, UNSET
from mollie.utils import get_security_from_env
from mollie.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, Mapping, Optional, Union


class TransfersSDK(BaseSDK):
    def create(
        self,
        *,
        x_client_signature: str,
        x_client_signed_at: str,
        idempotency_key: str,
        idempotency_key1: Optional[str] = None,
        transfer_request: Optional[
            Union[models.TransferRequest, models.TransferRequestTypedDict]
        ] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.TransferResponse:
        r"""Create transfer

        > 🚧 Beta feature
        >
        > This feature is currently in beta testing, and the final specification may still change.

        Create a SEPA Credit Transfer from your Mollie Business Account.

        To initiate a transfer, you must provide the transfer scheme, the amount, the debtor IBAN (your Mollie Business
        Account IBAN), and the creditor (recipient) details.

        Each request must include an `Idempotency-Key` header to prevent duplicate transfers, and must be signed using the
        `X-Client-Signature` and `X-Client-Signed-At` headers.

        ### Simulating transfer scenarios in test mode

        In test mode, you can simulate various transfer scenarios by adjusting the transfer amount. This allows you to
        mimic the typical status progression of a real-world transfer. Note that a transfer's progression will stop once
        it reaches a final status: `blocked`, `failed`, or `processed`.

        | Amount  | Scenario                                           | Webhook sequence                                                                                                                                                   |
        |---------|----------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|
        | `11.00` | Transfer initiated, pending review by Mollie       | `business-account-transfer.requested` → `business-account-transfer.initiated` → `business-account-transfer.pending-review`                                         |
        | `12.00` | Transfer initiated, blocked by Mollie              | `business-account-transfer.requested` → `business-account-transfer.initiated` → `business-account-transfer.pending-review` → `business-account-transfer.blocked`   |
        | `13.00` | Transfer initiated, failed on scheme submission    | `business-account-transfer.requested` → `business-account-transfer.initiated` → `business-account-transfer.failed`                                                 |
        | Other   | Default: transfer is processed                     | `business-account-transfer.requested` → `business-account-transfer.initiated` → `business-account-transfer.processed`                                              |

        If set, this operation will use `organization_access_token` from the global security.

        :param x_client_signature: A cryptographic signature of the request payload, used to verify the authenticity of the transfer request.
        :param x_client_signed_at: The timestamp (in ISO 8601 format) indicating when the client signed the request. Used in conjunction with
            `X-Client-Signature` for request verification.
        :param idempotency_key: A unique value used to identify this request and prevent duplicate transfers. UUIDv4 is recommended to
            guarantee uniqueness across multiple processes or servers. If two requests are received with the same
            idempotency key, the second request will be discarded.

            View the [public documentation](https://docs.mollie.com/reference/api-idempotency#using-an-idempotency-key)
            to learn more.
        :param idempotency_key1: A unique key to ensure idempotent requests. This key should be a UUID v4 string.
        :param transfer_request:
        :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.CreateTransferRequest(
            x_client_signature=x_client_signature,
            x_client_signed_at=x_client_signed_at,
            idempotency_key=idempotency_key,
            idempotency_key1=idempotency_key1,
            transfer_request=utils.get_pydantic_model(
                transfer_request, Optional[models.TransferRequest]
            ),
        )

        req = self._build_request(
            method="POST",
            path="/business-accounts/transfers",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/hal+json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.transfer_request if request is not None else None,
                False,
                True,
                "json",
                Optional[models.TransferRequest],
            ),
            allow_empty_value=None,
            allowed_fields=["organization_access_token"],
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 5000, 2, 7500), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5xx"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="create-transfer",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "503", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "201", "application/hal+json"):
            return unmarshal_json_response(models.TransferResponse, http_res)
        if utils.match_response(http_res, "422", "application/hal+json"):
            response_data = unmarshal_json_response(models.ErrorResponseData, http_res)
            raise models.ErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "503", "application/hal+json"):
            response_data = unmarshal_json_response(models.ErrorResponseData, http_res)
            raise models.ErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.APIError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.APIError("API error occurred", http_res, http_res_text)

        raise models.APIError("Unexpected response received", http_res)

    async def create_async(
        self,
        *,
        x_client_signature: str,
        x_client_signed_at: str,
        idempotency_key: str,
        idempotency_key1: Optional[str] = None,
        transfer_request: Optional[
            Union[models.TransferRequest, models.TransferRequestTypedDict]
        ] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.TransferResponse:
        r"""Create transfer

        > 🚧 Beta feature
        >
        > This feature is currently in beta testing, and the final specification may still change.

        Create a SEPA Credit Transfer from your Mollie Business Account.

        To initiate a transfer, you must provide the transfer scheme, the amount, the debtor IBAN (your Mollie Business
        Account IBAN), and the creditor (recipient) details.

        Each request must include an `Idempotency-Key` header to prevent duplicate transfers, and must be signed using the
        `X-Client-Signature` and `X-Client-Signed-At` headers.

        ### Simulating transfer scenarios in test mode

        In test mode, you can simulate various transfer scenarios by adjusting the transfer amount. This allows you to
        mimic the typical status progression of a real-world transfer. Note that a transfer's progression will stop once
        it reaches a final status: `blocked`, `failed`, or `processed`.

        | Amount  | Scenario                                           | Webhook sequence                                                                                                                                                   |
        |---------|----------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|
        | `11.00` | Transfer initiated, pending review by Mollie       | `business-account-transfer.requested` → `business-account-transfer.initiated` → `business-account-transfer.pending-review`                                         |
        | `12.00` | Transfer initiated, blocked by Mollie              | `business-account-transfer.requested` → `business-account-transfer.initiated` → `business-account-transfer.pending-review` → `business-account-transfer.blocked`   |
        | `13.00` | Transfer initiated, failed on scheme submission    | `business-account-transfer.requested` → `business-account-transfer.initiated` → `business-account-transfer.failed`                                                 |
        | Other   | Default: transfer is processed                     | `business-account-transfer.requested` → `business-account-transfer.initiated` → `business-account-transfer.processed`                                              |

        If set, this operation will use `organization_access_token` from the global security.

        :param x_client_signature: A cryptographic signature of the request payload, used to verify the authenticity of the transfer request.
        :param x_client_signed_at: The timestamp (in ISO 8601 format) indicating when the client signed the request. Used in conjunction with
            `X-Client-Signature` for request verification.
        :param idempotency_key: A unique value used to identify this request and prevent duplicate transfers. UUIDv4 is recommended to
            guarantee uniqueness across multiple processes or servers. If two requests are received with the same
            idempotency key, the second request will be discarded.

            View the [public documentation](https://docs.mollie.com/reference/api-idempotency#using-an-idempotency-key)
            to learn more.
        :param idempotency_key1: A unique key to ensure idempotent requests. This key should be a UUID v4 string.
        :param transfer_request:
        :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.CreateTransferRequest(
            x_client_signature=x_client_signature,
            x_client_signed_at=x_client_signed_at,
            idempotency_key=idempotency_key,
            idempotency_key1=idempotency_key1,
            transfer_request=utils.get_pydantic_model(
                transfer_request, Optional[models.TransferRequest]
            ),
        )

        req = self._build_request_async(
            method="POST",
            path="/business-accounts/transfers",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/hal+json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.transfer_request if request is not None else None,
                False,
                True,
                "json",
                Optional[models.TransferRequest],
            ),
            allow_empty_value=None,
            allowed_fields=["organization_access_token"],
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 5000, 2, 7500), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5xx"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="create-transfer",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "503", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "201", "application/hal+json"):
            return unmarshal_json_response(models.TransferResponse, http_res)
        if utils.match_response(http_res, "422", "application/hal+json"):
            response_data = unmarshal_json_response(models.ErrorResponseData, http_res)
            raise models.ErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "503", "application/hal+json"):
            response_data = unmarshal_json_response(models.ErrorResponseData, http_res)
            raise models.ErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.APIError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.APIError("API error occurred", http_res, http_res_text)

        raise models.APIError("Unexpected response received", http_res)

    def get(
        self,
        *,
        business_accounts_transfer_id: str,
        testmode: Optional[bool] = None,
        idempotency_key: Optional[str] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.TransferResponse:
        r"""Get transfer

        > 🚧 Beta feature
        >
        > This feature is currently in beta testing, and the final specification may still change.

        Retrieve a single transfer object by its transfer ID. This allows you to check the current status
        and details of a previously created transfer.

        If set, this operation will use `organization_access_token` from the global security.

        :param business_accounts_transfer_id: Provide the ID of the related transfer.
        :param testmode: Most API credentials are specifically created for either live mode or test mode. In those cases the `testmode` query
            parameter must not be sent. For organization-level credentials such as OAuth access tokens, you can enable test mode by
            setting the `testmode` query parameter to `true`.

            Test entities cannot be retrieved when the endpoint is set to live mode, and vice versa.
        :param idempotency_key: A unique key to ensure idempotent requests. This key should be a UUID v4 string.
        :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.GetTransferRequest(
            business_accounts_transfer_id=business_accounts_transfer_id,
            testmode=testmode,
            idempotency_key=idempotency_key,
        )

        req = self._build_request(
            method="GET",
            path="/business-accounts/transfers/{businessAccountsTransferId}",
            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/hal+json",
            http_headers=http_headers,
            _globals=models.GetTransferGlobals(
                testmode=self.sdk_configuration.globals.testmode,
            ),
            security=self.sdk_configuration.security,
            allow_empty_value=None,
            allowed_fields=["organization_access_token"],
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 5000, 2, 7500), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5xx"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="get-transfer",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["404", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/hal+json"):
            return unmarshal_json_response(models.TransferResponse, http_res)
        if utils.match_response(http_res, "404", "application/hal+json"):
            response_data = unmarshal_json_response(models.ErrorResponseData, http_res)
            raise models.ErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.APIError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.APIError("API error occurred", http_res, http_res_text)

        raise models.APIError("Unexpected response received", http_res)

    async def get_async(
        self,
        *,
        business_accounts_transfer_id: str,
        testmode: Optional[bool] = None,
        idempotency_key: Optional[str] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.TransferResponse:
        r"""Get transfer

        > 🚧 Beta feature
        >
        > This feature is currently in beta testing, and the final specification may still change.

        Retrieve a single transfer object by its transfer ID. This allows you to check the current status
        and details of a previously created transfer.

        If set, this operation will use `organization_access_token` from the global security.

        :param business_accounts_transfer_id: Provide the ID of the related transfer.
        :param testmode: Most API credentials are specifically created for either live mode or test mode. In those cases the `testmode` query
            parameter must not be sent. For organization-level credentials such as OAuth access tokens, you can enable test mode by
            setting the `testmode` query parameter to `true`.

            Test entities cannot be retrieved when the endpoint is set to live mode, and vice versa.
        :param idempotency_key: A unique key to ensure idempotent requests. This key should be a UUID v4 string.
        :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.GetTransferRequest(
            business_accounts_transfer_id=business_accounts_transfer_id,
            testmode=testmode,
            idempotency_key=idempotency_key,
        )

        req = self._build_request_async(
            method="GET",
            path="/business-accounts/transfers/{businessAccountsTransferId}",
            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/hal+json",
            http_headers=http_headers,
            _globals=models.GetTransferGlobals(
                testmode=self.sdk_configuration.globals.testmode,
            ),
            security=self.sdk_configuration.security,
            allow_empty_value=None,
            allowed_fields=["organization_access_token"],
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 5000, 2, 7500), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5xx"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="get-transfer",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["404", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/hal+json"):
            return unmarshal_json_response(models.TransferResponse, http_res)
        if utils.match_response(http_res, "404", "application/hal+json"):
            response_data = unmarshal_json_response(models.ErrorResponseData, http_res)
            raise models.ErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.APIError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.APIError("API error occurred", http_res, http_res_text)

        raise models.APIError("Unexpected response received", http_res)
