# coding: utf-8

"""
    Voucherify API

    Voucherify promotion engine REST API. Please see https://docs.voucherify.io/docs for more details.

    The version of the OpenAPI document: v2018-08-01
    Contact: support@voucherify.io
    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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from voucherify.models.order_calculated_item_product import OrderCalculatedItemProduct
from voucherify.models.order_calculated_item_sku import OrderCalculatedItemSku
from typing import Optional, Set
from typing_extensions import Self

class OrderCalculatedItem(BaseModel):
    """
    OrderCalculatedItem
    """ # noqa: E501
    id: Optional[StrictStr] = Field(default=None, description="Unique identifier of the order line item.")
    sku_id: Optional[StrictStr] = Field(default=None, description="Unique identifier of the SKU. It is assigned by Voucherify.")
    product_id: Optional[StrictStr] = Field(default=None, description="Unique identifier of the product. It is assigned by Voucherify.")
    related_object: Optional[StrictStr] = Field(default=None, description="Used along with the source_id property, can be set to either sku or product.")
    source_id: Optional[StrictStr] = Field(default=None, description="The merchant's product/SKU ID (if it is different from the Voucherify product/SKU ID). It is useful in the integration between multiple systems. It can be an ID from an eCommerce site, a database, or a third-party service.")
    quantity: Optional[StrictInt] = Field(default=None, description="The quantity of the particular item in the cart.")
    discount_quantity: Optional[StrictInt] = Field(default=None, description="Number of dicounted items.")
    initial_quantity: Optional[StrictInt] = Field(default=None, description="A positive integer in the smallest unit quantity representing the total amount of the order; this is the sum of the order items' quantity.")
    amount: Optional[StrictInt] = Field(default=None, description="The total amount of the order item (price * quantity).")
    discount_amount: Optional[StrictInt] = Field(default=None, description="Sum of all order-item-level discounts applied to the order.")
    applied_discount_amount: Optional[StrictInt] = Field(default=None, description="This field shows the order-level discount applied.")
    applied_discount_quantity: Optional[StrictInt] = Field(default=None, description="Number of the discounted items applied in the transaction.")
    applied_quantity: Optional[StrictInt] = Field(default=None, description="Quantity of items changed by the application of a new quantity items. It can be positive when an item is added or negative if an item is replaced.")
    applied_quantity_amount: Optional[StrictInt] = Field(default=None, description="Amount for the items changed by the application of a new quantity items. It can be positive when an item is added or negative if an item is replaced.")
    initial_amount: Optional[StrictInt] = Field(default=None, description="A positive integer in the smallest currency unit (e.g. 100 cents for $1.00) representing the total amount of the order. This is the sum of the order items' amounts.")
    price: Optional[StrictInt] = Field(default=None, description="Unit price of an item. The value is multiplied by 100 to represent 2 decimal places. For example `10000 cents` for `$100.00`.")
    subtotal_amount: Optional[StrictInt] = Field(default=None, description="Final order item amount after the applied item-level discount.  If there are no item-level discounts applied, this item is equal to the `amount`.    `subtotal_amount`=`amount`-`applied_discount_amount`")
    product: Optional[OrderCalculatedItemProduct] = None
    sku: Optional[OrderCalculatedItemSku] = None
    object: Optional[StrictStr] = Field(default='order_item', description="The type of the object represented by JSON.")
    metadata: Optional[Dict[str, Any]] = Field(default=None, description="A set of custom key/value pairs that you can attach to an item object. It can be useful for storing additional information about the item in a structured format. It can be used to define business validation rules or discount formulas.")
    __properties: ClassVar[List[str]] = ["id", "sku_id", "product_id", "related_object", "source_id", "quantity", "discount_quantity", "initial_quantity", "amount", "discount_amount", "applied_discount_amount", "applied_discount_quantity", "applied_quantity", "applied_quantity_amount", "initial_amount", "price", "subtotal_amount", "product", "sku", "object", "metadata"]

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

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

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

        if value not in set(['order_item']):
            raise ValueError("must be one of enum values ('order_item')")
        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 OrderCalculatedItem 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 product
        if self.product:
            _dict['product'] = self.product.to_dict()
        # override the default output from pydantic by calling `to_dict()` of sku
        if self.sku:
            _dict['sku'] = self.sku.to_dict()
        # set to None if id (nullable) is None
        # and model_fields_set contains the field
        if self.id is None and "id" in self.model_fields_set:
            _dict['id'] = None

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of OrderCalculatedItem 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"),
            "sku_id": obj.get("sku_id"),
            "product_id": obj.get("product_id"),
            "related_object": obj.get("related_object"),
            "source_id": obj.get("source_id"),
            "quantity": obj.get("quantity"),
            "discount_quantity": obj.get("discount_quantity"),
            "initial_quantity": obj.get("initial_quantity"),
            "amount": obj.get("amount"),
            "discount_amount": obj.get("discount_amount"),
            "applied_discount_amount": obj.get("applied_discount_amount"),
            "applied_discount_quantity": obj.get("applied_discount_quantity"),
            "applied_quantity": obj.get("applied_quantity"),
            "applied_quantity_amount": obj.get("applied_quantity_amount"),
            "initial_amount": obj.get("initial_amount"),
            "price": obj.get("price"),
            "subtotal_amount": obj.get("subtotal_amount"),
            "product": OrderCalculatedItemProduct.from_dict(obj["product"]) if obj.get("product") is not None else None,
            "sku": OrderCalculatedItemSku.from_dict(obj["sku"]) if obj.get("sku") is not None else None,
            "object": obj.get("object") if obj.get("object") is not None else 'order_item',
            "metadata": obj.get("metadata")
        })
        return _obj


