# coding: utf-8

"""
    Logto API references

    API references for Logto services. To learn more about how to interact with Logto APIs, see [Interact with Management API](https://docs.logto.io/docs/recipes/interact-with-management-api/).

    The version of the OpenAPI document: Cloud
    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, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from py_logto.models.api_configs_jwt_customizer_token_type_path_get200_response_one_of_context_sample_user_profile import ApiConfigsJwtCustomizerTokenTypePathGet200ResponseOneOfContextSampleUserProfile
from py_logto.models.api_users_user_id_patch_request_avatar import ApiUsersUserIdPatchRequestAvatar
from typing import Optional, Set
from typing_extensions import Self

class ApiUsersPostRequest(BaseModel):
    """
    User data to create a new user. All properties are optional.
    """ # noqa: E501
    primary_phone: Optional[Annotated[str, Field(strict=True)]] = Field(default=None, description="Primary phone number for the user. It should be unique across all users.", alias="primaryPhone")
    primary_email: Optional[Annotated[str, Field(strict=True)]] = Field(default=None, description="Primary email address for the user. It should be unique across all users.", alias="primaryEmail")
    username: Optional[Annotated[str, Field(strict=True)]] = Field(default=None, description="Username for the user. It should be unique across all users.")
    password: Optional[Annotated[str, Field(min_length=1, strict=True)]] = Field(default=None, description="Plain text password for the user.")
    password_digest: Optional[StrictStr] = Field(default=None, description="In case you already have the password digests and not the passwords, you can use them for the newly created user via this property. The value should be generated with one of the supported algorithms. The algorithm can be specified using the `passwordAlgorithm` property.", alias="passwordDigest")
    password_algorithm: Optional[StrictStr] = Field(default=None, description="The hash algorithm used for the password. It should be one of the supported algorithms: argon2, md5, sha1, sha256. Should the encryption algorithm differ from argon2, it will automatically be upgraded to argon2 upon the user's next sign-in.", alias="passwordAlgorithm")
    name: Optional[StrictStr] = None
    avatar: Optional[ApiUsersUserIdPatchRequestAvatar] = None
    custom_data: Optional[Dict[str, Any]] = Field(default=None, description="arbitrary", alias="customData")
    profile: Optional[ApiConfigsJwtCustomizerTokenTypePathGet200ResponseOneOfContextSampleUserProfile] = None
    __properties: ClassVar[List[str]] = ["primaryPhone", "primaryEmail", "username", "password", "passwordDigest", "passwordAlgorithm", "name", "avatar", "customData", "profile"]

    @field_validator('primary_phone')
    def primary_phone_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(r"^\d+$", value):
            raise ValueError(r"must validate the regular expression /^\d+$/")
        return value

    @field_validator('primary_email')
    def primary_email_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(r"^\S+@\S+\.\S+$", value):
            raise ValueError(r"must validate the regular expression /^\S+@\S+\.\S+$/")
        return value

    @field_validator('username')
    def username_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(r"^[A-Z_a-z]\w*$", value):
            raise ValueError(r"must validate the regular expression /^[A-Z_a-z]\w*$/")
        return value

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

        if value not in set(['Argon2i', 'SHA1', 'SHA256', 'MD5', 'Bcrypt']):
            raise ValueError("must be one of enum values ('Argon2i', 'SHA1', 'SHA256', 'MD5', 'Bcrypt')")
        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 ApiUsersPostRequest 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 avatar
        if self.avatar:
            _dict['avatar'] = self.avatar.to_dict()
        # override the default output from pydantic by calling `to_dict()` of profile
        if self.profile:
            _dict['profile'] = self.profile.to_dict()
        # set to None if avatar (nullable) is None
        # and model_fields_set contains the field
        if self.avatar is None and "avatar" in self.model_fields_set:
            _dict['avatar'] = None

        return _dict

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

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

        _obj = cls.model_validate({
            "primaryPhone": obj.get("primaryPhone"),
            "primaryEmail": obj.get("primaryEmail"),
            "username": obj.get("username"),
            "password": obj.get("password"),
            "passwordDigest": obj.get("passwordDigest"),
            "passwordAlgorithm": obj.get("passwordAlgorithm"),
            "name": obj.get("name"),
            "avatar": ApiUsersUserIdPatchRequestAvatar.from_dict(obj["avatar"]) if obj.get("avatar") is not None else None,
            "customData": obj.get("customData"),
            "profile": ApiConfigsJwtCustomizerTokenTypePathGet200ResponseOneOfContextSampleUserProfile.from_dict(obj["profile"]) if obj.get("profile") is not None else None
        })
        return _obj


