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

from __future__ import annotations
from .amount import Amount, AmountTypedDict
from .metadata import Metadata, MetadataTypedDict
from .mode import Mode
from .refund_external_reference_type_response import RefundExternalReferenceTypeResponse
from .url import URL, URLTypedDict
from .url_nullable import URLNullable, URLNullableTypedDict
from enum import Enum
from mollie import models, utils
from mollie.types import BaseModel, Nullable, OptionalNullable, UNSET, UNSET_SENTINEL
import pydantic
from pydantic import field_serializer, model_serializer
from typing import List, Optional
from typing_extensions import Annotated, NotRequired, TypedDict


class ListEntityRefundSettlementAmountTypedDict(TypedDict):
    r"""This optional field will contain the approximate amount that will be deducted from your account balance, converted
    to the currency your account is settled in.

    The amount is a **negative** amount.

    If the refund is not directly processed by Mollie, for example for PayPal refunds, the settlement amount will be
    zero.

    Since the field contains an estimated amount during refund processing, it may change over time. For example, while
    the refund is queued the settlement amount is likely not yet available.

    To retrieve accurate settlement amounts we recommend using the
    [List balance transactions endpoint](list-balance-transactions) instead.
    """

    currency: str
    r"""A three-character ISO 4217 currency code."""
    value: str
    r"""A string containing an exact monetary amount in the given currency."""


class ListEntityRefundSettlementAmount(BaseModel):
    r"""This optional field will contain the approximate amount that will be deducted from your account balance, converted
    to the currency your account is settled in.

    The amount is a **negative** amount.

    If the refund is not directly processed by Mollie, for example for PayPal refunds, the settlement amount will be
    zero.

    Since the field contains an estimated amount during refund processing, it may change over time. For example, while
    the refund is queued the settlement amount is likely not yet available.

    To retrieve accurate settlement amounts we recommend using the
    [List balance transactions endpoint](list-balance-transactions) instead.
    """

    currency: str
    r"""A three-character ISO 4217 currency code."""

    value: str
    r"""A string containing an exact monetary amount in the given currency."""


class ListEntityRefundStatus(str, Enum, metaclass=utils.OpenEnumMeta):
    QUEUED = "queued"
    PENDING = "pending"
    PROCESSING = "processing"
    REFUNDED = "refunded"
    FAILED = "failed"
    CANCELED = "canceled"


class ListEntityRefundExternalReferenceTypedDict(TypedDict):
    type: NotRequired[RefundExternalReferenceTypeResponse]
    r"""Specifies the reference type"""
    id: NotRequired[str]
    r"""Unique reference from the payment provider"""


class ListEntityRefundExternalReference(BaseModel):
    type: Optional[RefundExternalReferenceTypeResponse] = None
    r"""Specifies the reference type"""

    id: Optional[str] = None
    r"""Unique reference from the payment provider"""

    @field_serializer("type")
    def serialize_type(self, value):
        if isinstance(value, str):
            try:
                return models.RefundExternalReferenceTypeResponse(value)
            except ValueError:
                return value
        return value

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = set(["type", "id"])
        serialized = handler(self)
        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k, serialized.get(n))

            if val != UNSET_SENTINEL:
                if val is not None or k not in optional_fields:
                    m[k] = val

        return m


class ListEntityRefundSourceTypedDict(TypedDict):
    r"""Where the funds will be pulled back from."""

    organization_id: NotRequired[str]


class ListEntityRefundSource(BaseModel):
    r"""Where the funds will be pulled back from."""

    organization_id: Annotated[
        Optional[str], pydantic.Field(alias="organizationId")
    ] = None

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = set(["organizationId"])
        serialized = handler(self)
        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k, serialized.get(n))

            if val != UNSET_SENTINEL:
                if val is not None or k not in optional_fields:
                    m[k] = val

        return m


class ListEntityRefundRoutingReversalTypedDict(TypedDict):
    amount: NotRequired[AmountTypedDict]
    r"""In v2 endpoints, monetary amounts are represented as objects with a `currency` and `value` field."""
    source: NotRequired[ListEntityRefundSourceTypedDict]
    r"""Where the funds will be pulled back from."""


class ListEntityRefundRoutingReversal(BaseModel):
    amount: Optional[Amount] = None
    r"""In v2 endpoints, monetary amounts are represented as objects with a `currency` and `value` field."""

    source: Optional[ListEntityRefundSource] = None
    r"""Where the funds will be pulled back from."""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = set(["amount", "source"])
        serialized = handler(self)
        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k, serialized.get(n))

            if val != UNSET_SENTINEL:
                if val is not None or k not in optional_fields:
                    m[k] = val

        return m


class ListEntityRefundLinksTypedDict(TypedDict):
    r"""An object with several relevant URLs. Every URL object will contain an `href` and a `type` field."""

    self_: URLTypedDict
    r"""In v2 endpoints, URLs are commonly represented as objects with an `href` and `type` field."""
    payment: URLTypedDict
    r"""In v2 endpoints, URLs are commonly represented as objects with an `href` and `type` field."""
    settlement: NotRequired[Nullable[URLNullableTypedDict]]
    r"""In v2 endpoints, URLs are commonly represented as objects with an `href` and `type` field."""


class ListEntityRefundLinks(BaseModel):
    r"""An object with several relevant URLs. Every URL object will contain an `href` and a `type` field."""

    self_: Annotated[URL, pydantic.Field(alias="self")]
    r"""In v2 endpoints, URLs are commonly represented as objects with an `href` and `type` field."""

    payment: URL
    r"""In v2 endpoints, URLs are commonly represented as objects with an `href` and `type` field."""

    settlement: OptionalNullable[URLNullable] = UNSET
    r"""In v2 endpoints, URLs are commonly represented as objects with an `href` and `type` field."""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = set(["settlement"])
        nullable_fields = set(["settlement"])
        serialized = handler(self)
        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k, serialized.get(n))
            is_nullable_and_explicitly_set = (
                k in nullable_fields
                and (self.__pydantic_fields_set__.intersection({n}))  # pylint: disable=no-member
            )

            if val != UNSET_SENTINEL:
                if (
                    val is not None
                    or k not in optional_fields
                    or is_nullable_and_explicitly_set
                ):
                    m[k] = val

        return m


class ListEntityRefundTypedDict(TypedDict):
    resource: str
    r"""Indicates the response contains a refund object. Will always contain the string `refund` for this endpoint."""
    id: str
    r"""The identifier uniquely referring to this refund. Mollie assigns this identifier at refund creation time. Mollie
    will always refer to the refund by this ID. Example: `re_4qqhO89gsT`.
    """
    mode: Mode
    r"""Whether this entity was created in live mode or in test mode."""
    description: str
    r"""The description of the refund that may be shown to your customer, depending on the payment method used."""
    amount: AmountTypedDict
    r"""In v2 endpoints, monetary amounts are represented as objects with a `currency` and `value` field."""
    metadata: Nullable[MetadataTypedDict]
    r"""Provide any data you like, for example a string or a JSON object. We will save the data alongside the entity. Whenever
    you fetch the entity with our API, we will also include the metadata. You can use up to approximately 1kB.
    """
    status: ListEntityRefundStatus
    created_at: str
    r"""The entity's date and time of creation, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format."""
    links: ListEntityRefundLinksTypedDict
    r"""An object with several relevant URLs. Every URL object will contain an `href` and a `type` field."""
    settlement_amount: NotRequired[Nullable[ListEntityRefundSettlementAmountTypedDict]]
    r"""This optional field will contain the approximate amount that will be deducted from your account balance, converted
    to the currency your account is settled in.

    The amount is a **negative** amount.

    If the refund is not directly processed by Mollie, for example for PayPal refunds, the settlement amount will be
    zero.

    Since the field contains an estimated amount during refund processing, it may change over time. For example, while
    the refund is queued the settlement amount is likely not yet available.

    To retrieve accurate settlement amounts we recommend using the
    [List balance transactions endpoint](list-balance-transactions) instead.
    """
    payment_id: NotRequired[str]
    r"""The unique identifier of the payment this refund was created for.
    The full payment object can be retrieved via the payment URL in the `_links` object.
    """
    settlement_id: NotRequired[Nullable[str]]
    r"""The identifier referring to the settlement this refund was settled with. This field is omitted if the refund is not settled (yet)."""
    external_reference: NotRequired[ListEntityRefundExternalReferenceTypedDict]
    routing_reversals: NotRequired[
        Nullable[List[ListEntityRefundRoutingReversalTypedDict]]
    ]
    r"""*This feature is only available to marketplace operators.*

    When creating refunds for *routed* payments, by default the full amount is deducted from your balance.

    If you want to pull back funds from the connected merchant(s), you can use this parameter to specify what amount
    needs to be reversed from which merchant(s).

    If you simply want to fully reverse the routed funds, you can also use the `reverseRouting` parameter instead.
    """


class ListEntityRefund(BaseModel):
    resource: str
    r"""Indicates the response contains a refund object. Will always contain the string `refund` for this endpoint."""

    id: str
    r"""The identifier uniquely referring to this refund. Mollie assigns this identifier at refund creation time. Mollie
    will always refer to the refund by this ID. Example: `re_4qqhO89gsT`.
    """

    mode: Mode
    r"""Whether this entity was created in live mode or in test mode."""

    description: str
    r"""The description of the refund that may be shown to your customer, depending on the payment method used."""

    amount: Amount
    r"""In v2 endpoints, monetary amounts are represented as objects with a `currency` and `value` field."""

    metadata: Nullable[Metadata]
    r"""Provide any data you like, for example a string or a JSON object. We will save the data alongside the entity. Whenever
    you fetch the entity with our API, we will also include the metadata. You can use up to approximately 1kB.
    """

    status: ListEntityRefundStatus

    created_at: Annotated[str, pydantic.Field(alias="createdAt")]
    r"""The entity's date and time of creation, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format."""

    links: Annotated[ListEntityRefundLinks, pydantic.Field(alias="_links")]
    r"""An object with several relevant URLs. Every URL object will contain an `href` and a `type` field."""

    settlement_amount: Annotated[
        OptionalNullable[ListEntityRefundSettlementAmount],
        pydantic.Field(alias="settlementAmount"),
    ] = UNSET
    r"""This optional field will contain the approximate amount that will be deducted from your account balance, converted
    to the currency your account is settled in.

    The amount is a **negative** amount.

    If the refund is not directly processed by Mollie, for example for PayPal refunds, the settlement amount will be
    zero.

    Since the field contains an estimated amount during refund processing, it may change over time. For example, while
    the refund is queued the settlement amount is likely not yet available.

    To retrieve accurate settlement amounts we recommend using the
    [List balance transactions endpoint](list-balance-transactions) instead.
    """

    payment_id: Annotated[Optional[str], pydantic.Field(alias="paymentId")] = None
    r"""The unique identifier of the payment this refund was created for.
    The full payment object can be retrieved via the payment URL in the `_links` object.
    """

    settlement_id: Annotated[
        OptionalNullable[str], pydantic.Field(alias="settlementId")
    ] = UNSET
    r"""The identifier referring to the settlement this refund was settled with. This field is omitted if the refund is not settled (yet)."""

    external_reference: Annotated[
        Optional[ListEntityRefundExternalReference],
        pydantic.Field(alias="externalReference"),
    ] = None

    routing_reversals: Annotated[
        OptionalNullable[List[ListEntityRefundRoutingReversal]],
        pydantic.Field(alias="routingReversals"),
    ] = UNSET
    r"""*This feature is only available to marketplace operators.*

    When creating refunds for *routed* payments, by default the full amount is deducted from your balance.

    If you want to pull back funds from the connected merchant(s), you can use this parameter to specify what amount
    needs to be reversed from which merchant(s).

    If you simply want to fully reverse the routed funds, you can also use the `reverseRouting` parameter instead.
    """

    @field_serializer("mode")
    def serialize_mode(self, value):
        if isinstance(value, str):
            try:
                return models.Mode(value)
            except ValueError:
                return value
        return value

    @field_serializer("status")
    def serialize_status(self, value):
        if isinstance(value, str):
            try:
                return models.ListEntityRefundStatus(value)
            except ValueError:
                return value
        return value

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = set(
            [
                "settlementAmount",
                "paymentId",
                "settlementId",
                "externalReference",
                "routingReversals",
            ]
        )
        nullable_fields = set(
            ["settlementAmount", "metadata", "settlementId", "routingReversals"]
        )
        serialized = handler(self)
        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k, serialized.get(n))
            is_nullable_and_explicitly_set = (
                k in nullable_fields
                and (self.__pydantic_fields_set__.intersection({n}))  # pylint: disable=no-member
            )

            if val != UNSET_SENTINEL:
                if (
                    val is not None
                    or k not in optional_fields
                    or is_nullable_and_explicitly_set
                ):
                    m[k] = val

        return m


try:
    ListEntityRefundSource.model_rebuild()
except NameError:
    pass
try:
    ListEntityRefundLinks.model_rebuild()
except NameError:
    pass
try:
    ListEntityRefund.model_rebuild()
except NameError:
    pass
