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

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


class Grants(BaseSDK):
    def list(
        self,
        *,
        entitlement_id: str,
        limit: Optional[int] = 20,
        offset: Optional[int] = 0,
        include_voided: Optional[bool] = False,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ListEntitlementGrantsResponse:
        r"""List Grants

        List grants for a metered entitlement. Active grants are returned by default; pass `includeVoided=true` to include voided grants.

        :param entitlement_id: The unique identifier of the entitlement.
        :param limit: Maximum number of grants to return per page.
        :param offset: Number of grants to skip.
        :param include_voided: When true, voided grants are included in the response.
        :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.ListEntitlementGrantsRequest(
            entitlement_id=entitlement_id,
            limit=limit,
            offset=offset,
            include_voided=include_voided,
        )

        req = self._build_request(
            method="GET",
            path="/v1/entitlements/{entitlementId}/grants",
            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,
            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

        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="listEntitlementGrants",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "404", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(
                models.ListEntitlementGrantsResponse, http_res
            )
        if utils.match_response(http_res, "400", "application/json"):
            response_data = unmarshal_json_response(errors.BadRequestUnion, http_res)
            raise errors.BadRequest(response_data, http_res)
        if utils.match_response(http_res, ["403", "404"], "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "500", "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.PaygenticDefaultError(
                "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.PaygenticDefaultError(
                "API error occurred", http_res, http_res_text
            )

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

    async def list_async(
        self,
        *,
        entitlement_id: str,
        limit: Optional[int] = 20,
        offset: Optional[int] = 0,
        include_voided: Optional[bool] = False,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ListEntitlementGrantsResponse:
        r"""List Grants

        List grants for a metered entitlement. Active grants are returned by default; pass `includeVoided=true` to include voided grants.

        :param entitlement_id: The unique identifier of the entitlement.
        :param limit: Maximum number of grants to return per page.
        :param offset: Number of grants to skip.
        :param include_voided: When true, voided grants are included in the response.
        :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.ListEntitlementGrantsRequest(
            entitlement_id=entitlement_id,
            limit=limit,
            offset=offset,
            include_voided=include_voided,
        )

        req = self._build_request_async(
            method="GET",
            path="/v1/entitlements/{entitlementId}/grants",
            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,
            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

        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="listEntitlementGrants",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "404", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(
                models.ListEntitlementGrantsResponse, http_res
            )
        if utils.match_response(http_res, "400", "application/json"):
            response_data = unmarshal_json_response(errors.BadRequestUnion, http_res)
            raise errors.BadRequest(response_data, http_res)
        if utils.match_response(http_res, ["403", "404"], "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "500", "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.PaygenticDefaultError(
                "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.PaygenticDefaultError(
                "API error occurred", http_res, http_res_text
            )

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

    def create(
        self,
        *,
        entitlement_id: str,
        amount: float,
        idempotency_key: str,
        effective_at: Optional[datetime] = None,
        expires_at: OptionalNullable[datetime] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.Grant:
        r"""Create Grant

        Create a grant directly for a metered entitlement, crediting the customer's balance immediately. The entitlement must belong to an active v1 subscription.

        :param entitlement_id: The unique identifier of the entitlement to grant credits to.
        :param amount: The number of credits to grant.
        :param idempotency_key: Idempotency key to prevent duplicate grants. Must be unique per entitlement.
        :param effective_at: When the grant becomes effective. Defaults to now.
        :param expires_at: When the grant expires. If omitted, the grant does not expire.
        :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.CreateEntitlementGrantRequest(
            entitlement_id=entitlement_id,
            create_grant_request=models.CreateGrantRequest(
                amount=amount,
                effective_at=effective_at,
                expires_at=expires_at,
                idempotency_key=idempotency_key,
            ),
        )

        req = self._build_request(
            method="POST",
            path="/v1/entitlements/{entitlementId}/grants",
            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.create_grant_request,
                False,
                False,
                "json",
                models.CreateGrantRequest,
            ),
            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

        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="createEntitlementGrant",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "404", "409", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "201", "application/json"):
            return unmarshal_json_response(models.Grant, http_res)
        if utils.match_response(http_res, "400", "application/json"):
            response_data = unmarshal_json_response(errors.BadRequestUnion, http_res)
            raise errors.BadRequest(response_data, http_res)
        if utils.match_response(http_res, ["403", "404", "409"], "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "500", "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.PaygenticDefaultError(
                "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.PaygenticDefaultError(
                "API error occurred", http_res, http_res_text
            )

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

    async def create_async(
        self,
        *,
        entitlement_id: str,
        amount: float,
        idempotency_key: str,
        effective_at: Optional[datetime] = None,
        expires_at: OptionalNullable[datetime] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.Grant:
        r"""Create Grant

        Create a grant directly for a metered entitlement, crediting the customer's balance immediately. The entitlement must belong to an active v1 subscription.

        :param entitlement_id: The unique identifier of the entitlement to grant credits to.
        :param amount: The number of credits to grant.
        :param idempotency_key: Idempotency key to prevent duplicate grants. Must be unique per entitlement.
        :param effective_at: When the grant becomes effective. Defaults to now.
        :param expires_at: When the grant expires. If omitted, the grant does not expire.
        :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.CreateEntitlementGrantRequest(
            entitlement_id=entitlement_id,
            create_grant_request=models.CreateGrantRequest(
                amount=amount,
                effective_at=effective_at,
                expires_at=expires_at,
                idempotency_key=idempotency_key,
            ),
        )

        req = self._build_request_async(
            method="POST",
            path="/v1/entitlements/{entitlementId}/grants",
            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.create_grant_request,
                False,
                False,
                "json",
                models.CreateGrantRequest,
            ),
            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

        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="createEntitlementGrant",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "404", "409", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "201", "application/json"):
            return unmarshal_json_response(models.Grant, http_res)
        if utils.match_response(http_res, "400", "application/json"):
            response_data = unmarshal_json_response(errors.BadRequestUnion, http_res)
            raise errors.BadRequest(response_data, http_res)
        if utils.match_response(http_res, ["403", "404", "409"], "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "500", "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.PaygenticDefaultError(
                "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.PaygenticDefaultError(
                "API error occurred", http_res, http_res_text
            )

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

    def purchase(
        self,
        *,
        entitlement_id: str,
        amount: float,
        price: str,
        idempotency_key: str,
        effective_at: Optional[datetime] = None,
        expires_at: OptionalNullable[datetime] = UNSET,
        success_url: Optional[str] = None,
        cancel_url: Optional[str] = None,
        payment_expires_at: Optional[datetime] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.PurchaseGrantResponse:
        r"""Purchase Grant

        Create an ad-hoc invoice with a payment session for a grant purchase. The customer pays via the returned payment URL; the grant is created automatically on payment completion. If payment expires, the invoice is cancelled and no grant is created.

        After the consumer completes payment, the grant is created automatically. To confirm payment completion, poll `GET /v2/invoices/{invoiceId}` using the `invoiceId` from the response and check for `status === \"PAID\"`. Recommended polling interval: 2 seconds, timeout: 60 seconds.

        :param entitlement_id: The unique identifier of the entitlement to purchase credits for.
        :param amount: The number of credits to grant upon payment completion.
        :param price: The price in decimal format (e.g., '5.00' for $5.00 USD). Must be at least $0.50.
        :param idempotency_key: Caller-provided deduplication key. Retrying with the same key returns the existing invoice.
        :param effective_at: When the grant becomes effective. Defaults to now.
        :param expires_at: When the grant expires. If omitted, the grant does not expire.
        :param success_url: URL to redirect the customer to after successful payment.
        :param cancel_url: URL to redirect the customer to if payment is cancelled.
        :param payment_expires_at: When the payment session expires. If omitted, uses the default expiry.
        :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.PurchaseEntitlementGrantRequest(
            entitlement_id=entitlement_id,
            purchase_grant_request=models.PurchaseGrantRequest(
                amount=amount,
                price=price,
                idempotency_key=idempotency_key,
                effective_at=effective_at,
                expires_at=expires_at,
                success_url=success_url,
                cancel_url=cancel_url,
                payment_expires_at=payment_expires_at,
            ),
        )

        req = self._build_request(
            method="POST",
            path="/v1/entitlements/{entitlementId}/grants/purchase",
            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.purchase_grant_request,
                False,
                False,
                "json",
                models.PurchaseGrantRequest,
            ),
            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

        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="purchaseEntitlementGrant",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "404", "409", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "201", "application/json"):
            return unmarshal_json_response(models.PurchaseGrantResponse, http_res)
        if utils.match_response(http_res, "400", "application/json"):
            response_data = unmarshal_json_response(errors.BadRequestUnion, http_res)
            raise errors.BadRequest(response_data, http_res)
        if utils.match_response(http_res, ["403", "404", "409"], "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "500", "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.PaygenticDefaultError(
                "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.PaygenticDefaultError(
                "API error occurred", http_res, http_res_text
            )

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

    async def purchase_async(
        self,
        *,
        entitlement_id: str,
        amount: float,
        price: str,
        idempotency_key: str,
        effective_at: Optional[datetime] = None,
        expires_at: OptionalNullable[datetime] = UNSET,
        success_url: Optional[str] = None,
        cancel_url: Optional[str] = None,
        payment_expires_at: Optional[datetime] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.PurchaseGrantResponse:
        r"""Purchase Grant

        Create an ad-hoc invoice with a payment session for a grant purchase. The customer pays via the returned payment URL; the grant is created automatically on payment completion. If payment expires, the invoice is cancelled and no grant is created.

        After the consumer completes payment, the grant is created automatically. To confirm payment completion, poll `GET /v2/invoices/{invoiceId}` using the `invoiceId` from the response and check for `status === \"PAID\"`. Recommended polling interval: 2 seconds, timeout: 60 seconds.

        :param entitlement_id: The unique identifier of the entitlement to purchase credits for.
        :param amount: The number of credits to grant upon payment completion.
        :param price: The price in decimal format (e.g., '5.00' for $5.00 USD). Must be at least $0.50.
        :param idempotency_key: Caller-provided deduplication key. Retrying with the same key returns the existing invoice.
        :param effective_at: When the grant becomes effective. Defaults to now.
        :param expires_at: When the grant expires. If omitted, the grant does not expire.
        :param success_url: URL to redirect the customer to after successful payment.
        :param cancel_url: URL to redirect the customer to if payment is cancelled.
        :param payment_expires_at: When the payment session expires. If omitted, uses the default expiry.
        :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.PurchaseEntitlementGrantRequest(
            entitlement_id=entitlement_id,
            purchase_grant_request=models.PurchaseGrantRequest(
                amount=amount,
                price=price,
                idempotency_key=idempotency_key,
                effective_at=effective_at,
                expires_at=expires_at,
                success_url=success_url,
                cancel_url=cancel_url,
                payment_expires_at=payment_expires_at,
            ),
        )

        req = self._build_request_async(
            method="POST",
            path="/v1/entitlements/{entitlementId}/grants/purchase",
            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.purchase_grant_request,
                False,
                False,
                "json",
                models.PurchaseGrantRequest,
            ),
            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

        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="purchaseEntitlementGrant",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "404", "409", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "201", "application/json"):
            return unmarshal_json_response(models.PurchaseGrantResponse, http_res)
        if utils.match_response(http_res, "400", "application/json"):
            response_data = unmarshal_json_response(errors.BadRequestUnion, http_res)
            raise errors.BadRequest(response_data, http_res)
        if utils.match_response(http_res, ["403", "404", "409"], "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "500", "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.PaygenticDefaultError(
                "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.PaygenticDefaultError(
                "API error occurred", http_res, http_res_text
            )

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

    def get(
        self,
        *,
        entitlement_id: str,
        grant_id: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.Grant:
        r"""Get Grant

        Retrieve a specific grant by ID.

        :param entitlement_id: The unique identifier of the entitlement.
        :param grant_id: The unique identifier of the grant.
        :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.GetEntitlementGrantRequest(
            entitlement_id=entitlement_id,
            grant_id=grant_id,
        )

        req = self._build_request(
            method="GET",
            path="/v1/entitlements/{entitlementId}/grants/{grantId}",
            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,
            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

        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="getEntitlementGrant",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "404", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.Grant, http_res)
        if utils.match_response(http_res, "400", "application/json"):
            response_data = unmarshal_json_response(errors.BadRequestUnion, http_res)
            raise errors.BadRequest(response_data, http_res)
        if utils.match_response(http_res, ["403", "404"], "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "500", "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.PaygenticDefaultError(
                "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.PaygenticDefaultError(
                "API error occurred", http_res, http_res_text
            )

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

    async def get_async(
        self,
        *,
        entitlement_id: str,
        grant_id: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.Grant:
        r"""Get Grant

        Retrieve a specific grant by ID.

        :param entitlement_id: The unique identifier of the entitlement.
        :param grant_id: The unique identifier of the grant.
        :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.GetEntitlementGrantRequest(
            entitlement_id=entitlement_id,
            grant_id=grant_id,
        )

        req = self._build_request_async(
            method="GET",
            path="/v1/entitlements/{entitlementId}/grants/{grantId}",
            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,
            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

        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="getEntitlementGrant",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "404", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.Grant, http_res)
        if utils.match_response(http_res, "400", "application/json"):
            response_data = unmarshal_json_response(errors.BadRequestUnion, http_res)
            raise errors.BadRequest(response_data, http_res)
        if utils.match_response(http_res, ["403", "404"], "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "500", "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.PaygenticDefaultError(
                "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.PaygenticDefaultError(
                "API error occurred", http_res, http_res_text
            )

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

    def void(
        self,
        *,
        entitlement_id: str,
        grant_id: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.Grant:
        r"""Void Grant

        Void a grant, removing it from the customer's balance. This operation is idempotent — voiding an already-voided grant returns the voided grant without error.

        :param entitlement_id: The unique identifier of the entitlement.
        :param grant_id: The unique identifier of the grant to void.
        :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.VoidEntitlementGrantRequest(
            entitlement_id=entitlement_id,
            grant_id=grant_id,
        )

        req = self._build_request(
            method="DELETE",
            path="/v1/entitlements/{entitlementId}/grants/{grantId}",
            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,
            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

        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="voidEntitlementGrant",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "404", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.Grant, http_res)
        if utils.match_response(http_res, "400", "application/json"):
            response_data = unmarshal_json_response(errors.BadRequestUnion, http_res)
            raise errors.BadRequest(response_data, http_res)
        if utils.match_response(http_res, ["403", "404"], "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "500", "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.PaygenticDefaultError(
                "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.PaygenticDefaultError(
                "API error occurred", http_res, http_res_text
            )

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

    async def void_async(
        self,
        *,
        entitlement_id: str,
        grant_id: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.Grant:
        r"""Void Grant

        Void a grant, removing it from the customer's balance. This operation is idempotent — voiding an already-voided grant returns the voided grant without error.

        :param entitlement_id: The unique identifier of the entitlement.
        :param grant_id: The unique identifier of the grant to void.
        :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.VoidEntitlementGrantRequest(
            entitlement_id=entitlement_id,
            grant_id=grant_id,
        )

        req = self._build_request_async(
            method="DELETE",
            path="/v1/entitlements/{entitlementId}/grants/{grantId}",
            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,
            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

        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="voidEntitlementGrant",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "404", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.Grant, http_res)
        if utils.match_response(http_res, "400", "application/json"):
            response_data = unmarshal_json_response(errors.BadRequestUnion, http_res)
            raise errors.BadRequest(response_data, http_res)
        if utils.match_response(http_res, ["403", "404"], "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "500", "application/json"):
            response_data = unmarshal_json_response(errors.ErrorData, http_res)
            raise errors.Error(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.PaygenticDefaultError(
                "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.PaygenticDefaultError(
                "API error occurred", http_res, http_res_text
            )

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