# The Okta software accompanied by this notice is provided pursuant to the following terms:
# Copyright © 2025-Present, Okta, Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
# License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS
# IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under the License.
# coding: utf-8

"""
Okta Admin Management

Allows customers to easily access the Okta Management APIs

The version of the OpenAPI document: 5.1.0
Contact: devex-public@okta.com
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 datetime import datetime
from typing import Any, ClassVar, Dict, List
from typing import Optional, Set

from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator
from typing_extensions import Self

from okta.models.user_credentials import UserCredentials
from okta.models.user_links import UserLinks
from okta.models.user_profile import UserProfile
from okta.models.user_status import UserStatus
from okta.models.user_type import UserType


class User(BaseModel):
    """
    User
    """  # noqa: E501

    activated: Optional[datetime] = Field(
        default=None,
        description="The timestamp when the user status transitioned to `ACTIVE`",
    )
    created: Optional[datetime] = Field(
        default=None, description="The timestamp when the user was created"
    )
    credentials: Optional[UserCredentials] = None
    id: Optional[StrictStr] = Field(
        default=None, description="The unique key for the user"
    )
    last_login: Optional[datetime] = Field(
        default=None, description="The timestamp of the last login", alias="lastLogin"
    )
    last_updated: Optional[datetime] = Field(
        default=None,
        description="The timestamp when the user was last updated",
        alias="lastUpdated",
    )
    password_changed: Optional[datetime] = Field(
        default=None,
        description="The timestamp when the user's password was last updated",
        alias="passwordChanged",
    )
    profile: Optional[UserProfile] = None
    realm_id: Optional[StrictStr] = Field(
        default=None,
        description="The ID of the realm in which the user is residing. See [Realms]("
        "/openapi/okta-management/management/tag/Realm/).",
        alias="realmId",
    )
    status: Optional[UserStatus] = None
    status_changed: Optional[datetime] = Field(
        default=None,
        description="The timestamp when the status of the user last changed",
        alias="statusChanged",
    )
    transitioning_to_status: Optional[StrictStr] = Field(
        default=None,
        description="The target status of an in-progress asynchronous status transition. This property is only returned if "
        "the user's state is transitioning.",
        alias="transitioningToStatus",
    )
    type: Optional[UserType] = None
    embedded: Optional[Dict[str, Dict[str, Any]]] = Field(
        default=None,
        description="Embedded resources related to the user using the [JSON Hypertext Application Language]("
        "https://datatracker.ietf.org/doc/html/draft-kelly-json-hal-06) specification",
        alias="_embedded",
    )
    links: Optional[UserLinks] = Field(default=None, alias="_links")
    __properties: ClassVar[List[str]] = [
        "activated",
        "created",
        "credentials",
        "id",
        "lastLogin",
        "lastUpdated",
        "passwordChanged",
        "profile",
        "realmId",
        "status",
        "statusChanged",
        "transitioningToStatus",
        "type",
        "_embedded",
        "_links",
    ]

    @field_validator("transitioning_to_status")
    def transitioning_to_status_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(["ACTIVE", "DEPROVISIONED", "PROVISIONED"]):
            raise ValueError(
                "must be one of enum values ('ACTIVE', 'DEPROVISIONED', 'PROVISIONED')"
            )
        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 User 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.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        """
        excluded_fields: Set[str] = set(
            [
                "activated",
                "created",
                "id",
                "last_login",
                "last_updated",
                "password_changed",
                "realm_id",
                "status_changed",
                "transitioning_to_status",
                "embedded",
            ]
        )

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of credentials
        if self.credentials:
            if not isinstance(self.credentials, dict):
                _dict["credentials"] = self.credentials.to_dict()
            else:
                _dict["credentials"] = self.credentials

        # override the default output from pydantic by calling `to_dict()` of profile
        if self.profile:
            if not isinstance(self.profile, dict):
                _dict["profile"] = self.profile.to_dict()
            else:
                _dict["profile"] = self.profile

        # override the default output from pydantic by calling `to_dict()` of type
        if self.type:
            if not isinstance(self.type, dict):
                _dict["type"] = self.type.to_dict()
            else:
                _dict["type"] = self.type

        # override the default output from pydantic by calling `to_dict()` of links
        if self.links:
            if not isinstance(self.links, dict):
                _dict["_links"] = self.links.to_dict()
            else:
                _dict["_links"] = self.links

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

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

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

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

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

        return _dict

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

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

        _obj = cls.model_validate(
            {
                "activated": obj.get("activated"),
                "created": obj.get("created"),
                "credentials": (
                    UserCredentials.from_dict(obj["credentials"])
                    if obj.get("credentials") is not None
                    else None
                ),
                "id": obj.get("id"),
                "lastLogin": obj.get("lastLogin"),
                "lastUpdated": obj.get("lastUpdated"),
                "passwordChanged": obj.get("passwordChanged"),
                "profile": (
                    UserProfile.from_dict(obj["profile"])
                    if obj.get("profile") is not None
                    else None
                ),
                "realmId": obj.get("realmId"),
                "status": obj.get("status"),
                "statusChanged": obj.get("statusChanged"),
                "transitioningToStatus": obj.get("transitioningToStatus"),
                "type": (
                    UserType.from_dict(obj["type"])
                    if obj.get("type") is not None
                    else None
                ),
                "_embedded": obj.get("_embedded"),
                "_links": (
                    UserLinks.from_dict(obj["_links"])
                    if obj.get("_links") is not None
                    else None
                ),
            }
        )
        return _obj
