# coding: utf-8

"""
    Wink Payment API

    A programmatic way to create bookings, receive reactive and disburse funds globally.  ## APIs Not every integrator needs every APIs. For that reason, we have separated APIs into context.  - [Affiliate](/affiliate): All APIs related to selling travel inventory as an affiliate. - [Analytics](/analytics): All APIs related to tracking metrics across a wide variety of data source segments including, more entertaining, leaderboard metrics. - [Booking](/booking): All APIs related to creating platform bookings. - [Channel Manager](/channel-manager): All APIs related to channel managers who want to integrate with our platform. - [Extranet](/extranet): All APIs related to managing travel inventory and suppliers. - [Inventory](/inventory): All APIs related to retrieve known travel inventory as it was found using the Lookup API.. - [Lookup](/lookup): All APIs related to locating inventory by region, locale and property flags. - [Reference](/reference): All APIs related to retrieving platform-supported taxonomies. - [TripPay](/reactive): All APIs related to TripPay account management, booking, mapping and integration features.  ## SDKs We are actively working on supporting the most used languages out there. If you don't see your language here, reach out to us with a request to officially add your language. In the meantime, if you want to roll your own SDK, you can do so by downloading the OpenAPI spec and using one of the many available OpenAPI generators available: [https://openapi-generator.tech/docs/generators](https://openapi-generator.tech/docs/generators).  - Java SDK [https://github.com/wink-travel/trip-pay-sdk-java](https://github.com/wink-travel/trip-pay-sdk-java)  # Usage These features are made available to you via a [REST API](https://en.wikipedia.org/wiki/Representational_state_transfer). This API is language agnostic. We will link to SDKs for the most popular programming languages on this page as they become available.  ## Versioning We chose to version our endpoints in a way that we hope affects your integration with us the least. You request the version of our API you wish to work with via the `Wink-Version` header. When it's time for you to upgrade, you only have to change the version number to get access to our updated endpoints.  ## Release history - Follow updates on Github: https://github.com/wink-travel/wink-sdk-java/blob/master/CHANGELOG.md 

    The version of the OpenAPI document: 30.16.4
    Contact: bjorn@wink.travel
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from trip_pay_payment.models.custom_monetary_amount import CustomMonetaryAmount
from typing import Optional, Set
from typing_extensions import Self

class Refund(BaseModel):
    """
    Refund objects allow you to refund a charge that has previously been created but not yet refunded. Funds will be refunded to the credit or debit card that was originally charged.
    """ # noqa: E501
    identifier: StrictStr = Field(description="A unique identifier")
    acquirer_refund_identifier: Optional[StrictStr] = Field(default=None, description="The acquirer refund identifier. Will get attached once it comes in on the webhook.", alias="acquirerRefundIdentifier")
    requested_by_identifier: Optional[StrictStr] = Field(default=None, description="The SSO person / entity that requested the refund.", alias="requestedByIdentifier")
    refund: CustomMonetaryAmount
    created: datetime = Field(description="When the amount was refunded")
    description: StrictStr = Field(description="A description of the refund that can be displayed to booker")
    reason_type: StrictStr = Field(description="A description of the refund that can be displayed to booker", alias="reasonType")
    cancel_on_refund: StrictStr = Field(description="Whether to cancel the booking alongside requesting a refund.", alias="cancelOnRefund")
    status_type: StrictStr = Field(description="Status of the refund", alias="statusType")
    request_type: StrictStr = Field(description="The entity making the refund request", alias="requestType")
    request_status: StrictStr = Field(description="Status of the refund request", alias="requestStatus")
    request_response: StrictStr = Field(description="Admin may choose to respond to the refund request made by the hotel", alias="requestResponse")
    receipt_url: Optional[StrictStr] = Field(default=None, description="This is the receipt url that contains a friendly web confirmation page. Comes in on the webhook.", alias="receiptUrl")
    retries: Optional[StrictInt] = Field(default=0, description="In case a TripPay admin has to go in and re-send the refund request to Stripe, we want to not to the same calculations again when a retry is executed so we keep track of retries here.")
    allocation: Optional[StrictStr] = Field(default='EQUAL_DISTRIBUTION', description="The type of refund determines how the funds are deducted each beneficiary.")
    __properties: ClassVar[List[str]] = ["identifier", "acquirerRefundIdentifier", "requestedByIdentifier", "refund", "created", "description", "reasonType", "cancelOnRefund", "statusType", "requestType", "requestStatus", "requestResponse", "receiptUrl", "retries", "allocation"]

    @field_validator('reason_type')
    def reason_type_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['DUPLICATE', 'FRAUDULENT', 'REQUESTED_BY_CUSTOMER', 'GUEST_COMPLAINT', 'GUEST_BOOKED_INCORRECT_DATE', 'GUEST_SICK', 'OVERBOOKING', 'EMERGENCY', 'FLIGHT_CANCELLED', 'DEATH_IN_FAMILY', 'OTHER', 'EXPIRED_UNCAPTURED_CHARGE']):
            raise ValueError("must be one of enum values ('DUPLICATE', 'FRAUDULENT', 'REQUESTED_BY_CUSTOMER', 'GUEST_COMPLAINT', 'GUEST_BOOKED_INCORRECT_DATE', 'GUEST_SICK', 'OVERBOOKING', 'EMERGENCY', 'FLIGHT_CANCELLED', 'DEATH_IN_FAMILY', 'OTHER', 'EXPIRED_UNCAPTURED_CHARGE')")
        return value

    @field_validator('cancel_on_refund')
    def cancel_on_refund_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['NONE', 'CANCEL_ON_SUCCESSFUL_REFUND', 'CANCEL_REGARDLESS']):
            raise ValueError("must be one of enum values ('NONE', 'CANCEL_ON_SUCCESSFUL_REFUND', 'CANCEL_REGARDLESS')")
        return value

    @field_validator('status_type')
    def status_type_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['PENDING', 'SUCCEEDED', 'CANCELED', 'REQUIRES_ACTION', 'FAILED']):
            raise ValueError("must be one of enum values ('PENDING', 'SUCCEEDED', 'CANCELED', 'REQUIRES_ACTION', 'FAILED')")
        return value

    @field_validator('request_type')
    def request_type_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['BY_SUPPLIER', 'BY_ADMIN', 'BY_STRIPE', 'BY_SYSTEM', 'BY_AGENT']):
            raise ValueError("must be one of enum values ('BY_SUPPLIER', 'BY_ADMIN', 'BY_STRIPE', 'BY_SYSTEM', 'BY_AGENT')")
        return value

    @field_validator('request_status')
    def request_status_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['PENDING', 'APPROVED', 'REJECTED']):
            raise ValueError("must be one of enum values ('PENDING', 'APPROVED', 'REJECTED')")
        return value

    @field_validator('allocation')
    def allocation_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(['FROM_SALE_ONLY', 'EQUAL_DISTRIBUTION', 'CUSTOMERS_ONLY']):
            raise ValueError("must be one of enum values ('FROM_SALE_ONLY', 'EQUAL_DISTRIBUTION', 'CUSTOMERS_ONLY')")
        return value

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.model_dump(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of Refund from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        """
        excluded_fields: Set[str] = set([
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of refund
        if self.refund:
            _dict['refund'] = self.refund.to_dict()
        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of Refund from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        _obj = cls.model_validate({
            "identifier": obj.get("identifier"),
            "acquirerRefundIdentifier": obj.get("acquirerRefundIdentifier"),
            "requestedByIdentifier": obj.get("requestedByIdentifier"),
            "refund": CustomMonetaryAmount.from_dict(obj["refund"]) if obj.get("refund") is not None else None,
            "created": obj.get("created"),
            "description": obj.get("description"),
            "reasonType": obj.get("reasonType"),
            "cancelOnRefund": obj.get("cancelOnRefund"),
            "statusType": obj.get("statusType"),
            "requestType": obj.get("requestType"),
            "requestStatus": obj.get("requestStatus"),
            "requestResponse": obj.get("requestResponse"),
            "receiptUrl": obj.get("receiptUrl"),
            "retries": obj.get("retries") if obj.get("retries") is not None else 0,
            "allocation": obj.get("allocation") if obj.get("allocation") is not None else 'EQUAL_DISTRIBUTION'
        })
        return _obj


