"""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, Dict, List, Mapping, Optional, Union


class UsageEvents(BaseSDK):
    def create(
        self,
        *,
        customer_id: str,
        idempotency_key: str,
        merchant_id: str,
        properties: Union[
            List[models.CreateUsageEventRequestProperty],
            List[models.CreateUsageEventRequestPropertyTypedDict],
        ],
        timestamp: datetime,
        entitlement_id: Optional[str] = None,
        metadata: Optional[Dict[str, 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.UsageEvent:
        r"""Create

        Creates a usage event. The idempotencyKey is used to ensure the event is processed only once by downstream consumers, even if the same event is submitted multiple times. Duplicate submissions will be accepted and return the same response.

        :param customer_id: Customer identifier that generated this consumption event. Sample values: 'cus_abc123xyz', 'cus_789def456'
        :param idempotency_key: Unique deduplication key preventing duplicate event processing. Sample values: 'usg_2024_01_15_abc123', 'event_wallet_xyz789', 'consumption_ref_456def'
        :param merchant_id: Merchant organization identifier owning this consumption event. Sample values: 'org_abc123xyz', 'org_789def456'
        :param properties:
        :param timestamp: Actual occurrence timestamp for the consumption event in ISO 8601 format. Sample values: '2024-01-15T10:30:00Z', '2024-02-01T14:45:30Z'. Represents when the event occurred, not when Paygentic received it.
        :param entitlement_id: Commitment identifier for this consumption event. Sample values: 'com_abc123xyz', 'com_789def456'
        :param metadata: Custom key-value attributes providing context about the consumption event. Sample values: {\"model_name\": \"claude-3-opus\", \"input_tokens\": \"1500\", \"output_tokens\": \"800\"} or {\"storage_tier\": \"premium\", \"data_center\": \"eu-west-1\", \"encryption\": \"enabled\"} or {\"image_resolution\": \"1024x1024\", \"generation_model\": \"stable-diffusion-xl\"}
        :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.CreateUsageEventRequest(
            customer_id=customer_id,
            entitlement_id=entitlement_id,
            idempotency_key=idempotency_key,
            merchant_id=merchant_id,
            metadata=metadata,
            properties=utils.get_pydantic_model(
                properties, List[models.CreateUsageEventRequestProperty]
            ),
            timestamp=timestamp,
        )

        req = self._build_request(
            method="POST",
            path="/v0/usage",
            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.CreateUsageEventRequest
            ),
            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="createUsageEvent",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "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.UsageEvent, 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", "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,
        *,
        customer_id: str,
        idempotency_key: str,
        merchant_id: str,
        properties: Union[
            List[models.CreateUsageEventRequestProperty],
            List[models.CreateUsageEventRequestPropertyTypedDict],
        ],
        timestamp: datetime,
        entitlement_id: Optional[str] = None,
        metadata: Optional[Dict[str, 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.UsageEvent:
        r"""Create

        Creates a usage event. The idempotencyKey is used to ensure the event is processed only once by downstream consumers, even if the same event is submitted multiple times. Duplicate submissions will be accepted and return the same response.

        :param customer_id: Customer identifier that generated this consumption event. Sample values: 'cus_abc123xyz', 'cus_789def456'
        :param idempotency_key: Unique deduplication key preventing duplicate event processing. Sample values: 'usg_2024_01_15_abc123', 'event_wallet_xyz789', 'consumption_ref_456def'
        :param merchant_id: Merchant organization identifier owning this consumption event. Sample values: 'org_abc123xyz', 'org_789def456'
        :param properties:
        :param timestamp: Actual occurrence timestamp for the consumption event in ISO 8601 format. Sample values: '2024-01-15T10:30:00Z', '2024-02-01T14:45:30Z'. Represents when the event occurred, not when Paygentic received it.
        :param entitlement_id: Commitment identifier for this consumption event. Sample values: 'com_abc123xyz', 'com_789def456'
        :param metadata: Custom key-value attributes providing context about the consumption event. Sample values: {\"model_name\": \"claude-3-opus\", \"input_tokens\": \"1500\", \"output_tokens\": \"800\"} or {\"storage_tier\": \"premium\", \"data_center\": \"eu-west-1\", \"encryption\": \"enabled\"} or {\"image_resolution\": \"1024x1024\", \"generation_model\": \"stable-diffusion-xl\"}
        :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.CreateUsageEventRequest(
            customer_id=customer_id,
            entitlement_id=entitlement_id,
            idempotency_key=idempotency_key,
            merchant_id=merchant_id,
            metadata=metadata,
            properties=utils.get_pydantic_model(
                properties, List[models.CreateUsageEventRequestProperty]
            ),
            timestamp=timestamp,
        )

        req = self._build_request_async(
            method="POST",
            path="/v0/usage",
            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.CreateUsageEventRequest
            ),
            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="createUsageEvent",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "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.UsageEvent, 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", "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 list(
        self,
        *,
        end_time: datetime,
        start_time: datetime,
        consumer_id: Optional[str] = None,
        customer_id: Optional[str] = None,
        limit: Optional[int] = 10,
        merchant_id: Optional[str] = None,
        offset: Optional[int] = 0,
        subscription_id: 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.ListUsageEventsResponse:
        r"""List

        :param end_time: ISO 8601 date-time string filtering events up to this timestamp. Sample values: '2024-01-31T23:59:59Z', '2024-02-28T12:00:00Z'
        :param start_time: ISO 8601 date-time string filtering events from this timestamp onward. Sample values: '2024-01-15T00:00:00Z', '2024-02-01T10:30:00Z'
        :param consumer_id: Filter by consumer ID. This is only available if the caller is member of the consumer organization.
        :param customer_id: Filter by customer ID. This is only available if the caller is member of the merchant organization owning this customer.
        :param limit: Number of usage events to return
        :param merchant_id: Filter by merchant ID. This is only available if the caller is member of the merchant organization.
        :param offset: Number of usage events to skip
        :param subscription_id: Filter by subscription ID. This is only available if the caller is member of the consumer or merchant organization owning this subscription.
        :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.ListUsageEventsRequest(
            consumer_id=consumer_id,
            customer_id=customer_id,
            end_time=end_time,
            limit=limit,
            merchant_id=merchant_id,
            offset=offset,
            start_time=start_time,
            subscription_id=subscription_id,
        )

        req = self._build_request(
            method="GET",
            path="/v0/usage",
            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/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="listUsageEvents",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "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.ListUsageEventsResponse, 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", "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,
        *,
        end_time: datetime,
        start_time: datetime,
        consumer_id: Optional[str] = None,
        customer_id: Optional[str] = None,
        limit: Optional[int] = 10,
        merchant_id: Optional[str] = None,
        offset: Optional[int] = 0,
        subscription_id: 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.ListUsageEventsResponse:
        r"""List

        :param end_time: ISO 8601 date-time string filtering events up to this timestamp. Sample values: '2024-01-31T23:59:59Z', '2024-02-28T12:00:00Z'
        :param start_time: ISO 8601 date-time string filtering events from this timestamp onward. Sample values: '2024-01-15T00:00:00Z', '2024-02-01T10:30:00Z'
        :param consumer_id: Filter by consumer ID. This is only available if the caller is member of the consumer organization.
        :param customer_id: Filter by customer ID. This is only available if the caller is member of the merchant organization owning this customer.
        :param limit: Number of usage events to return
        :param merchant_id: Filter by merchant ID. This is only available if the caller is member of the merchant organization.
        :param offset: Number of usage events to skip
        :param subscription_id: Filter by subscription ID. This is only available if the caller is member of the consumer or merchant organization owning this subscription.
        :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.ListUsageEventsRequest(
            consumer_id=consumer_id,
            customer_id=customer_id,
            end_time=end_time,
            limit=limit,
            merchant_id=merchant_id,
            offset=offset,
            start_time=start_time,
            subscription_id=subscription_id,
        )

        req = self._build_request_async(
            method="GET",
            path="/v0/usage",
            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/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="listUsageEvents",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "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.ListUsageEventsResponse, 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", "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,
        *,
        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.UsageEvent:
        r"""Get

        :param id:
        :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.GetUsageEventRequest(
            id=id,
        )

        req = self._build_request(
            method="GET",
            path="/v0/usage/{id}",
            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="getUsageEvent",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["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.UsageEvent, 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,
        *,
        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.UsageEvent:
        r"""Get

        :param id:
        :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.GetUsageEventRequest(
            id=id,
        )

        req = self._build_request_async(
            method="GET",
            path="/v0/usage/{id}",
            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="getUsageEvent",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["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.UsageEvent, 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 refund(
        self,
        *,
        id: str,
        refunded: bool,
        reason: 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.UsageEvent:
        r"""Refund

        Marks a usage event as refunded. This reverts the consumption recorded by the usage event and creates a corresponding refund billing event if the usage event was already billed.

        :param id:
        :param refunded: Set to true to mark the usage event as refunded. Once refunded, the event cannot be un-refunded.
        :param reason: Optional reason for the refund. Sample values: 'Customer request', 'Billing error', 'Service credit', 'System error correction'
        :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.RefundUsageEventRequest(
            id=id,
            request_body=models.RefundUsageEventRequestBody(
                refunded=refunded,
                reason=reason,
            ),
        )

        req = self._build_request(
            method="PATCH",
            path="/v0/usage/{id}",
            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.request_body,
                False,
                False,
                "json",
                models.RefundUsageEventRequestBody,
            ),
            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="refundUsageEvent",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "404", "422", "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.UsageEvent, 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", "422"], "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 refund_async(
        self,
        *,
        id: str,
        refunded: bool,
        reason: 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.UsageEvent:
        r"""Refund

        Marks a usage event as refunded. This reverts the consumption recorded by the usage event and creates a corresponding refund billing event if the usage event was already billed.

        :param id:
        :param refunded: Set to true to mark the usage event as refunded. Once refunded, the event cannot be un-refunded.
        :param reason: Optional reason for the refund. Sample values: 'Customer request', 'Billing error', 'Service credit', 'System error correction'
        :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.RefundUsageEventRequest(
            id=id,
            request_body=models.RefundUsageEventRequestBody(
                refunded=refunded,
                reason=reason,
            ),
        )

        req = self._build_request_async(
            method="PATCH",
            path="/v0/usage/{id}",
            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.request_body,
                False,
                False,
                "json",
                models.RefundUsageEventRequestBody,
            ),
            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="refundUsageEvent",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "404", "422", "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.UsageEvent, 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", "422"], "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 batch_create(
        self,
        *,
        events: Union[
            List[models.CreateUsageEventRequest],
            List[models.CreateUsageEventRequestTypedDict],
        ],
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.BatchUsageEventResponse:
        r"""Batch Create

        Creates multiple usage events in a single request. The idempotencyKey for each event is used to ensure the event is processed only once by downstream consumers, even if the same event is submitted multiple times. Duplicate submissions will be accepted and return the same response.

        :param events:
        :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.BatchCreateUsageEventsRequest(
            events=utils.get_pydantic_model(
                events, List[models.CreateUsageEventRequest]
            ),
        )

        req = self._build_request(
            method="POST",
            path="/v0/usage/batch",
            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.BatchCreateUsageEventsRequest
            ),
            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="batchCreateUsageEvents",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, ["201", "207"], "application/json"):
            return unmarshal_json_response(models.BatchUsageEventResponse, 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", "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 batch_create_async(
        self,
        *,
        events: Union[
            List[models.CreateUsageEventRequest],
            List[models.CreateUsageEventRequestTypedDict],
        ],
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.BatchUsageEventResponse:
        r"""Batch Create

        Creates multiple usage events in a single request. The idempotencyKey for each event is used to ensure the event is processed only once by downstream consumers, even if the same event is submitted multiple times. Duplicate submissions will be accepted and return the same response.

        :param events:
        :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.BatchCreateUsageEventsRequest(
            events=utils.get_pydantic_model(
                events, List[models.CreateUsageEventRequest]
            ),
        )

        req = self._build_request_async(
            method="POST",
            path="/v0/usage/batch",
            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.BatchCreateUsageEventsRequest
            ),
            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="batchCreateUsageEvents",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "403", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, ["201", "207"], "application/json"):
            return unmarshal_json_response(models.BatchUsageEventResponse, 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", "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)
