# coding: utf-8

"""
    PAY.JP API v2

    No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)

    The version of the OpenAPI document: 2.0.0
    Contact: support@pay.jp
    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, StrictBool, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from payjpv2.models.capture_method import CaptureMethod
from payjpv2.models.currency import Currency
from payjpv2.models.metadata_value import MetadataValue
from payjpv2.models.payment_flow_status import PaymentFlowStatus
from payjpv2.models.payment_method_types import PaymentMethodTypes
from typing import Optional, Set
from typing_extensions import Self

class PaymentFlowResponse(BaseModel):
    """
    PaymentFlowResponse
    """ # noqa: E501
    id: StrictStr = Field(description="支払いフローID")
    object: Optional[StrictStr] = 'payment_flow'
    created_at: datetime = Field(description="作成日時 (UTC, ISO 8601 形式)")
    updated_at: datetime = Field(description="更新日時 (UTC, ISO 8601 形式)")
    livemode: StrictBool = Field(description="本番環境かどうか")
    amount: StrictInt = Field(description="支払い予定の金額")
    currency: Currency = Field(description="価格の通貨。現在は `jpy` のみサポートしています。")
    amount_capturable: Optional[StrictInt]
    amount_received: Optional[StrictInt]
    client_secret: StrictStr = Field(description="このPaymentFlowのクライアントシークレットです。フロントエンドで公開APIキーと合わせて使用しPaymentFlowの情報を取得や支払い処理を行います。**この値はこのPaymentFlowの支払いを行う顧客以外へ公開しないでください。**また保存やログへの記録なども行わないでください。")
    customer_id: Optional[StrictStr]
    description: Optional[StrictStr]
    metadata: Dict[str, MetadataValue] = Field(description="メタデータ")
    payment_method_id: Optional[StrictStr]
    payment_method_options: Optional[Dict[str, Any]]
    payment_method_types: List[PaymentMethodTypes] = Field(description="このPaymentFlowで使用できる支払い方法の種類のリスト")
    status: PaymentFlowStatus = Field(description="このPaymentFlowのステータス。<a href=\"https://docs.pay.jp/v2/payment_flows#status\" target=\"_blank\">ステータスの詳細についてはこちらをご覧ください。</a>  | 値 | |:---| | **requires_payment_method**: 支払い方法が必要です。 | | **requires_confirmation**: 確認が必要です。 | | **requires_action**: 顧客のアクションが必要です。 | | **processing**: 処理中です。 | | **requires_capture**: 確定が必要です。 | | **canceled**: キャンセルされました。 | | **succeeded**: 成功しました。 |")
    next_action: Optional[Dict[str, Any]]
    return_url: Optional[StrictStr]
    capture_method: CaptureMethod = Field(description="支払いの確定方法  | 指定できる値 | |:---| | **automatic**: (デフォルト) 顧客が支払いを承認すると、自動的に確定させます。 | | **manual**: 顧客が支払いを承認すると一旦確定を保留し、後で Capture API を使用して確定します。（すべての支払い方法がこれをサポートしているわけではありません）。 |")
    last_payment_error: Optional[Dict[str, Any]]
    __properties: ClassVar[List[str]] = ["id", "object", "created_at", "updated_at", "livemode", "amount", "currency", "amount_capturable", "amount_received", "client_secret", "customer_id", "description", "metadata", "payment_method_id", "payment_method_options", "payment_method_types", "status", "next_action", "return_url", "capture_method", "last_payment_error"]

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

        if value not in set(['payment_flow']):
            raise ValueError("must be one of enum values ('payment_flow')")
        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"""
        return json.dumps(self.model_dump(by_alias=True, exclude_unset=True))

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of PaymentFlowResponse 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 each value in metadata (dict)
        _field_dict = {}
        if self.metadata:
            for _key_metadata in self.metadata:
                if self.metadata[_key_metadata]:
                    _field_dict[_key_metadata] = self.metadata[_key_metadata].to_dict()
            _dict['metadata'] = _field_dict
        # set to None if amount_capturable (nullable) is None
        # and model_fields_set contains the field
        if self.amount_capturable is None and "amount_capturable" in self.model_fields_set:
            _dict['amount_capturable'] = None

        # set to None if amount_received (nullable) is None
        # and model_fields_set contains the field
        if self.amount_received is None and "amount_received" in self.model_fields_set:
            _dict['amount_received'] = None

        # set to None if customer_id (nullable) is None
        # and model_fields_set contains the field
        if self.customer_id is None and "customer_id" in self.model_fields_set:
            _dict['customer_id'] = None

        # set to None if description (nullable) is None
        # and model_fields_set contains the field
        if self.description is None and "description" in self.model_fields_set:
            _dict['description'] = None

        # set to None if payment_method_id (nullable) is None
        # and model_fields_set contains the field
        if self.payment_method_id is None and "payment_method_id" in self.model_fields_set:
            _dict['payment_method_id'] = None

        # set to None if payment_method_options (nullable) is None
        # and model_fields_set contains the field
        if self.payment_method_options is None and "payment_method_options" in self.model_fields_set:
            _dict['payment_method_options'] = None

        # set to None if next_action (nullable) is None
        # and model_fields_set contains the field
        if self.next_action is None and "next_action" in self.model_fields_set:
            _dict['next_action'] = None

        # set to None if return_url (nullable) is None
        # and model_fields_set contains the field
        if self.return_url is None and "return_url" in self.model_fields_set:
            _dict['return_url'] = None

        # set to None if last_payment_error (nullable) is None
        # and model_fields_set contains the field
        if self.last_payment_error is None and "last_payment_error" in self.model_fields_set:
            _dict['last_payment_error'] = None

        return _dict

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

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

        _obj = cls.model_validate({
            "id": obj.get("id"),
            "object": obj.get("object") if obj.get("object") is not None else 'payment_flow',
            "created_at": obj.get("created_at"),
            "updated_at": obj.get("updated_at"),
            "livemode": obj.get("livemode"),
            "amount": obj.get("amount"),
            "currency": obj.get("currency"),
            "amount_capturable": obj.get("amount_capturable"),
            "amount_received": obj.get("amount_received"),
            "client_secret": obj.get("client_secret"),
            "customer_id": obj.get("customer_id"),
            "description": obj.get("description"),
            "metadata": dict(
                (_k, MetadataValue.from_dict(_v))
                for _k, _v in obj["metadata"].items()
            )
            if obj.get("metadata") is not None
            else None,
            "payment_method_id": obj.get("payment_method_id"),
            "payment_method_options": obj.get("payment_method_options"),
            "payment_method_types": obj.get("payment_method_types"),
            "status": obj.get("status"),
            "next_action": obj.get("next_action"),
            "return_url": obj.get("return_url"),
            "capture_method": obj.get("capture_method"),
            "last_payment_error": obj.get("last_payment_error")
        })
        return _obj


