# 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 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.pre_registration_inline_hook import PreRegistrationInlineHook
from okta.models.profile_enrollment_policy_rule_activation_requirement import (
    ProfileEnrollmentPolicyRuleActivationRequirement,
)
from okta.models.profile_enrollment_policy_rule_profile_attribute import (
    ProfileEnrollmentPolicyRuleProfileAttribute,
)


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

    access: Optional[StrictStr] = Field(
        default=None,
        description="Indicates if the user profile is granted access  > **Note:** You can't set the `access` property to "
        "`DENY` after you create the policy",
    )
    activation_requirements: Optional[
        ProfileEnrollmentPolicyRuleActivationRequirement
    ] = Field(default=None, alias="activationRequirements")
    allowed_identifiers: Optional[List[StrictStr]] = Field(
        default=None,
        description="A list of attributes to identify an end user. Can be used across Okta sign-in, unlock, and recovery "
        "flows.",
        alias="allowedIdentifiers",
    )
    enroll_authenticator_types: Optional[List[StrictStr]] = Field(
        default=None,
        description="Additional authenticator fields that can be used on the first page of user registration. Valid values "
        "only includes `'password'`.",
        alias="enrollAuthenticatorTypes",
    )
    pre_registration_inline_hooks: Optional[List[PreRegistrationInlineHook]] = Field(
        default=None,
        description="(Optional) The `id` of at most one registration inline hook",
        alias="preRegistrationInlineHooks",
    )
    profile_attributes: Optional[List[ProfileEnrollmentPolicyRuleProfileAttribute]] = (
        Field(
            default=None,
            description="A list of attributes to prompt the user for during registration or progressive profiling. Where "
            "defined on the user schema, these attributes are persisted in the user profile. You can also add "
            "non-schema attributes, which aren't persisted to the user's profile, but are included in requests "
            "to the registration inline hook. A maximum of 10 profile properties is supported.",
            alias="profileAttributes",
        )
    )
    progressive_profiling_action: Optional[StrictStr] = Field(
        default=None,
        description="Progressive profile enrollment helps evaluate the user profile policy at every user login. Users can be "
        "prompted to provide input for newly required attributes.",
        alias="progressiveProfilingAction",
    )
    target_group_ids: Optional[List[StrictStr]] = Field(
        default=None,
        description="(Optional, max 1 entry) The `id` of a group that this user should be added to",
        alias="targetGroupIds",
    )
    ui_schema_id: Optional[StrictStr] = Field(
        default=None,
        description="Value created by the backend. If present, all policy updates must include this attribute/value.",
        alias="uiSchemaId",
    )
    unknown_user_action: Optional[StrictStr] = Field(
        default=None,
        description="Which action should be taken if this user is new",
        alias="unknownUserAction",
    )
    __properties: ClassVar[List[str]] = [
        "access",
        "activationRequirements",
        "allowedIdentifiers",
        "enrollAuthenticatorTypes",
        "preRegistrationInlineHooks",
        "profileAttributes",
        "progressiveProfilingAction",
        "targetGroupIds",
        "uiSchemaId",
        "unknownUserAction",
    ]

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

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

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

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

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

        if value not in set(["DENY", "REGISTER"]):
            raise ValueError("must be one of enum values ('DENY', 'REGISTER')")
        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 ProfileEnrollmentPolicyRuleAction 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 activation_requirements
        if self.activation_requirements:
            if not isinstance(self.activation_requirements, dict):
                _dict["activationRequirements"] = self.activation_requirements.to_dict()
            else:
                _dict["activationRequirements"] = self.activation_requirements

        # override the default output from pydantic by calling `to_dict()` of each item in pre_registration_inline_hooks (list)
        _items = []
        if self.pre_registration_inline_hooks:
            for _item in self.pre_registration_inline_hooks:
                if _item:
                    _items.append(_item.to_dict())
            _dict["preRegistrationInlineHooks"] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in profile_attributes (list)
        _items = []
        if self.profile_attributes:
            for _item in self.profile_attributes:
                if _item:
                    _items.append(_item.to_dict())
            _dict["profileAttributes"] = _items
        return _dict

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

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

        _obj = cls.model_validate(
            {
                "access": obj.get("access"),
                "activationRequirements": (
                    ProfileEnrollmentPolicyRuleActivationRequirement.from_dict(
                        obj["activationRequirements"]
                    )
                    if obj.get("activationRequirements") is not None
                    else None
                ),
                "allowedIdentifiers": obj.get("allowedIdentifiers"),
                "enrollAuthenticatorTypes": obj.get("enrollAuthenticatorTypes"),
                "preRegistrationInlineHooks": (
                    [
                        PreRegistrationInlineHook.from_dict(_item)
                        for _item in obj["preRegistrationInlineHooks"]
                    ]
                    if obj.get("preRegistrationInlineHooks") is not None
                    else None
                ),
                "profileAttributes": (
                    [
                        ProfileEnrollmentPolicyRuleProfileAttribute.from_dict(_item)
                        for _item in obj["profileAttributes"]
                    ]
                    if obj.get("profileAttributes") is not None
                    else None
                ),
                "progressiveProfilingAction": obj.get("progressiveProfilingAction"),
                "targetGroupIds": obj.get("targetGroupIds"),
                "uiSchemaId": obj.get("uiSchemaId"),
                "unknownUserAction": obj.get("unknownUserAction"),
            }
        )
        return _obj
