# coding: utf-8

"""
Payment API

API for accepting payments and storing subscriptions

The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)

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


from __future__ import annotations

import json
import pprint
import re  # noqa: F401
from typing import Any, ClassVar, Dict, List, Optional, Set, Union

from pydantic import (
    BaseModel,
    ConfigDict,
    Field,
    StrictBool,
    StrictInt,
    StrictStr,
    field_validator,
)
from typing_extensions import Annotated, Self


class Coupon(BaseModel):
    """
    Model for reading a coupon
    """  # noqa: E501

    created_at: StrictInt = Field(description="Timestamp of creation")
    updated_at: StrictInt = Field(description="Timestamp of last update")
    id: StrictStr = Field(description="Unique identifier for the resource")
    code: Optional[Annotated[str, Field(min_length=4, strict=True, max_length=32)]] = (
        None
    )
    name: StrictStr = Field(
        description="A name for the coupon, e.g. 'Black Friday 2025'"
    )
    discount: Union[
        Annotated[float, Field(le=1.0, strict=True, ge=0.0)],
        Annotated[int, Field(le=1, strict=True, ge=0)],
    ] = Field(description="Discount percentage as a decimal")
    valid_until: Optional[StrictInt] = None
    valid_from: Optional[StrictInt] = None
    usage_limit: Optional[StrictInt] = None
    products: Optional[List[StrictStr]] = None
    is_active: Optional[StrictBool] = Field(
        default=True, description="Coupon is active"
    )
    usage_count: StrictInt = Field(description="Coupon usage count")
    payment_required: StrictBool = Field(
        description="Whether the coupon requires a payment. If the discount is not 100%, the coupon requires a payment."
    )
    is_valid: StrictBool = Field(
        description="Coupon is valid if it is active, not expired, and has not reached the usage limit"
    )
    __properties: ClassVar[List[str]] = [
        "created_at",
        "updated_at",
        "id",
        "code",
        "name",
        "discount",
        "valid_until",
        "valid_from",
        "usage_limit",
        "products",
        "is_active",
        "usage_count",
        "payment_required",
        "is_valid",
    ]

    @field_validator("code")
    def code_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(r"^[A-Z0-9]+$", value):
            raise ValueError(r"must validate the regular expression /^[A-Z0-9]+$/")
        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 Coupon 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.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        """
        excluded_fields: Set[str] = set(
            [
                "payment_required",
                "is_valid",
            ]
        )

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # set to None if code (nullable) is None
        # and model_fields_set contains the field
        if self.code is None and "code" in self.model_fields_set:
            _dict["code"] = None

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

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

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

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

        return _dict

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

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

        _obj = cls.model_validate(
            {
                "created_at": obj.get("created_at"),
                "updated_at": obj.get("updated_at"),
                "id": obj.get("id"),
                "code": obj.get("code"),
                "name": obj.get("name"),
                "discount": obj.get("discount"),
                "valid_until": obj.get("valid_until"),
                "valid_from": obj.get("valid_from"),
                "usage_limit": obj.get("usage_limit"),
                "products": obj.get("products"),
                "is_active": (
                    obj.get("is_active") if obj.get("is_active") is not None else True
                ),
                "usage_count": obj.get("usage_count"),
                "payment_required": obj.get("payment_required"),
                "is_valid": obj.get("is_valid"),
            }
        )
        return _obj
