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

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


class Payments(BaseSDK):
    r"""Pay for bookings using a card or bank account, and view payment
    status and history.

    > warn
    > Bookings usually expire within 1 hour so you'll need to make your payment
    > before the expiry date

    """

    def create_booking_payment(
        self,
        *,
        booking_id: str,
        amount: Optional[float] = None,
        currency: Optional[models.Currency] = None,
        source: Optional[Union[models.Source, models.SourceTypedDict]] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.CreateBookingPaymentResponse:
        r"""Pay for a Booking

        A payment is an attempt to pay for the booking, which will confirm the booking for the user and enable them to get their tickets.

        :param booking_id: The ID of the booking to pay for.
        :param amount: Amount intended to be collected by this payment. A positive decimal figure describing the amount to be collected.
        :param currency: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase.
        :param source: The payment source to take the payment from. This can be a card or a bank account. Some of these properties will be hidden on read to protect PII leaking.
        :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.CreateBookingPaymentRequest(
            booking_id=booking_id,
            body=models.BookingPayment(
                amount=amount,
                currency=currency,
                source=utils.get_pydantic_model(source, Optional[models.Source]),
            ),
        )

        req = self._build_request(
            method="POST",
            path="/bookings/{bookingId}/payment",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            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,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.body, False, False, "json", models.BookingPayment
            ),
            allow_empty_value=None,
            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, 60000, 1.5, 3600000), 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-booking-payment",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "401", "403", "429", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        if utils.match_response(http_res, "200", "application/json"):
            return models.CreateBookingPaymentResponse(
                result=unmarshal_json_response(
                    models.CreateBookingPaymentResponseBody, http_res
                ),
                headers=utils.get_response_headers(http_res.headers),
            )
        if utils.match_response(http_res, ["400", "401", "403", "429"], "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.TrainTravelDefaultError(
                "API error occurred", http_res, http_res_text
            )
        if utils.match_response(http_res, "500", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.TrainTravelDefaultError(
                "API error occurred", http_res, http_res_text
            )
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.TrainTravelDefaultError(
                "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 errors.TrainTravelDefaultError(
                "API error occurred", http_res, http_res_text
            )

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

    async def create_booking_payment_async(
        self,
        *,
        booking_id: str,
        amount: Optional[float] = None,
        currency: Optional[models.Currency] = None,
        source: Optional[Union[models.Source, models.SourceTypedDict]] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.CreateBookingPaymentResponse:
        r"""Pay for a Booking

        A payment is an attempt to pay for the booking, which will confirm the booking for the user and enable them to get their tickets.

        :param booking_id: The ID of the booking to pay for.
        :param amount: Amount intended to be collected by this payment. A positive decimal figure describing the amount to be collected.
        :param currency: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase.
        :param source: The payment source to take the payment from. This can be a card or a bank account. Some of these properties will be hidden on read to protect PII leaking.
        :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.CreateBookingPaymentRequest(
            booking_id=booking_id,
            body=models.BookingPayment(
                amount=amount,
                currency=currency,
                source=utils.get_pydantic_model(source, Optional[models.Source]),
            ),
        )

        req = self._build_request_async(
            method="POST",
            path="/bookings/{bookingId}/payment",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            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,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.body, False, False, "json", models.BookingPayment
            ),
            allow_empty_value=None,
            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, 60000, 1.5, 3600000), 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-booking-payment",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "401", "403", "429", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        if utils.match_response(http_res, "200", "application/json"):
            return models.CreateBookingPaymentResponse(
                result=unmarshal_json_response(
                    models.CreateBookingPaymentResponseBody, http_res
                ),
                headers=utils.get_response_headers(http_res.headers),
            )
        if utils.match_response(http_res, ["400", "401", "403", "429"], "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.TrainTravelDefaultError(
                "API error occurred", http_res, http_res_text
            )
        if utils.match_response(http_res, "500", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.TrainTravelDefaultError(
                "API error occurred", http_res, http_res_text
            )
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.TrainTravelDefaultError(
                "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 errors.TrainTravelDefaultError(
                "API error occurred", http_res, http_res_text
            )

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