# 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
from typing_extensions import Self

from okta.models.access_token_key_encryption_algorithm import (
    AccessTokenKeyEncryptionAlgorithm,
)
from okta.models.auth_server_links import AuthServerLinks
from okta.models.authorization_server_credentials import AuthorizationServerCredentials
from okta.models.lifecycle_status import LifecycleStatus
from okta.models.resource_server_json_web_keys import ResourceServerJsonWebKeys


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

    access_token_encrypted_response_algorithm: Optional[
        AccessTokenKeyEncryptionAlgorithm
    ] = Field(default=None, alias="accessTokenEncryptedResponseAlgorithm")
    audiences: Optional[List[StrictStr]] = Field(
        default=None,
        description="The recipients that the tokens are intended for. This becomes the `aud` claim in an access token. Okta "
        "currently supports only one audience.",
    )
    created: Optional[datetime] = None
    credentials: Optional[AuthorizationServerCredentials] = None
    description: Optional[StrictStr] = Field(
        default=None, description="The description of the custom authorization server"
    )
    id: Optional[StrictStr] = Field(
        default=None, description="The ID of the custom authorization server"
    )
    issuer: Optional[StrictStr] = Field(
        default=None,
        description="The complete URL for the custom authorization server. This becomes the `iss` claim in an access token.",
    )
    issuer_mode: Optional[StrictStr] = Field(
        default=None,
        description="Indicates which value is specified in the issuer of the tokens that a custom authorization server "
        "returns: the Okta org domain URL or a custom domain URL.  `issuerMode` is visible if you have a custom "
        "URL domain configured or the Dynamic Issuer Mode feature enabled. If you have a custom URL domain "
        "configured, you can set a custom domain URL in a custom authorization server, and this property is "
        "returned in the appropriate responses.  When set to `ORG_URL`, then in responses, `issuer` is the Okta "
        "org domain URL: `https://${yourOktaDomain}`.  When set to `CUSTOM_URL`, then in responses, `issuer` is "
        "the custom domain URL configured in the administration user interface.  When set to `DYNAMIC`, "
        "then in responses, `issuer` is the custom domain URL if the OAuth 2.0 request was sent to the custom "
        "domain, or is the Okta org's domain URL if the OAuth 2.0 request was sent to the original Okta org "
        "domain.  After you configure a custom URL domain, all new custom authorization servers use `CUSTOM_URL` "
        "by default. If the Dynamic Issuer Mode feature is enabled, then all new custom authorization servers "
        "use `DYNAMIC` by default. All existing custom authorization servers continue to use the original value "
        "until they're changed using the Admin Console or the API. This way, existing integrations with the "
        "client and resource server continue to work after the feature is enabled.",
        alias="issuerMode",
    )
    jwks: Optional[ResourceServerJsonWebKeys] = None
    jwks_uri: Optional[StrictStr] = Field(
        default=None,
        description='<x-lifecycle-container><x-lifecycle class="ea"></x-lifecycle></x-lifecycle-container>URL string that '
        "references a JSON Web Key Set for encrypting JWTs minted by the custom authorization server",
    )
    last_updated: Optional[datetime] = Field(default=None, alias="lastUpdated")
    name: Optional[StrictStr] = Field(
        default=None, description="The name of the custom authorization server"
    )
    status: Optional[LifecycleStatus] = None
    links: Optional[AuthServerLinks] = Field(default=None, alias="_links")
    __properties: ClassVar[List[str]] = [
        "accessTokenEncryptedResponseAlgorithm",
        "audiences",
        "created",
        "credentials",
        "description",
        "id",
        "issuer",
        "issuerMode",
        "jwks",
        "jwks_uri",
        "lastUpdated",
        "name",
        "status",
        "_links",
    ]

    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 AuthorizationServer 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.
        """
        excluded_fields: Set[str] = set(
            [
                "created",
                "id",
                "last_updated",
            ]
        )

        _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 jwks
        if self.jwks:
            if not isinstance(self.jwks, dict):
                _dict["jwks"] = self.jwks.to_dict()
            else:
                _dict["jwks"] = self.jwks

        # 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

        return _dict

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

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

        _obj = cls.model_validate(
            {
                "accessTokenEncryptedResponseAlgorithm": obj.get(
                    "accessTokenEncryptedResponseAlgorithm"
                ),
                "audiences": obj.get("audiences"),
                "created": obj.get("created"),
                "credentials": (
                    AuthorizationServerCredentials.from_dict(obj["credentials"])
                    if obj.get("credentials") is not None
                    else None
                ),
                "description": obj.get("description"),
                "id": obj.get("id"),
                "issuer": obj.get("issuer"),
                "issuerMode": obj.get("issuerMode"),
                "jwks": (
                    ResourceServerJsonWebKeys.from_dict(obj["jwks"])
                    if obj.get("jwks") is not None
                    else None
                ),
                "jwks_uri": obj.get("jwks_uri"),
                "lastUpdated": obj.get("lastUpdated"),
                "name": obj.get("name"),
                "status": obj.get("status"),
                "_links": (
                    AuthServerLinks.from_dict(obj["_links"])
                    if obj.get("_links") is not None
                    else None
                ),
            }
        )
        return _obj
