# coding: utf-8

"""
Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.
"""
from __future__ import annotations

from json import loads
from typing import Any, Dict, List, Optional, Self

from pydantic import BaseModel, Field, StrictInt, StrictStr

from algoliasearch.search.models.search_params_object import SearchParamsObject


class SecuredAPIKeyRestrictions(BaseModel):
    """
    SecuredAPIKeyRestrictions
    """

    search_params: Optional[SearchParamsObject] = Field(
        default=None, alias="searchParams"
    )
    filters: Optional[StrictStr] = Field(
        default=None,
        description="Filters that apply to every search made with the secured API key. You can add extra filters at search time with the filters query parameter. For example, if you set the filter group:admin on your generated API key, and you add groups:press OR groups:visitors with the filters query parameter, your final search filter is equivalent to groups:admin AND (groups:press OR groups:visitors). ",
    )
    valid_until: Optional[StrictInt] = Field(
        default=None,
        description="Unix timestamp used to set the expiration date of the API key.",
        alias="validUntil",
    )
    restrict_indices: Optional[List[StrictStr]] = Field(
        default=None,
        description="Index names that can be queried.",
        alias="restrictIndices",
    )
    restrict_sources: Optional[StrictStr] = Field(
        default=None,
        description="IPv4 network allowed to use the generated key. Use this to protect against API key leaking and reuse. You can only provide a single source, but you can specify a range of IPs (for example, 192.168.1.0/24). ",
        alias="restrictSources",
    )
    user_token: Optional[StrictStr] = Field(
        default=None,
        description="Unique user IP address. This can be useful when you want to impose a rate limit on specific users. By default, rate limits are set based on the IP address. This can become an issue when several users search from the same IP address. To avoid this, you can set a unique userToken for each user when generating their API key. This lets you restrict each user to a maximum number of API calls per hour, even if they share their IP with another user. Specifying the userToken in a secured API key is also a good security practice as it ensures users don't change it. Many features like Analytics, Personalization, and Dynamic Re-ranking rely on the authenticity of user identifiers. Setting the userToken at the API key level ensures that downstream services work as expected and prevents abuse. ",
        alias="userToken",
    )

    model_config = {"populate_by_name": True, "validate_assignment": True}

    def to_json(self) -> str:
        return self.model_dump_json(by_alias=True, exclude_unset=True)

    @classmethod
    def from_json(cls, json_str: str) -> Self:
        """Create an instance of SecuredAPIKeyRestrictions from a JSON string"""
        return cls.from_dict(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.
        """
        _dict = self.model_dump(
            by_alias=True,
            exclude={},
            exclude_none=True,
        )
        if self.search_params:
            _dict["searchParams"] = self.search_params.to_dict()
        return _dict

    @classmethod
    def from_dict(cls, obj: Dict) -> Self:
        """Create an instance of SecuredAPIKeyRestrictions from a dict"""
        if obj is None:
            return None

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

        _obj = cls.model_validate(
            {
                "searchParams": SearchParamsObject.from_dict(obj.get("searchParams"))
                if obj.get("searchParams") is not None
                else None,
                "filters": obj.get("filters"),
                "validUntil": obj.get("validUntil"),
                "restrictIndices": obj.get("restrictIndices"),
                "restrictSources": obj.get("restrictSources"),
                "userToken": obj.get("userToken"),
            }
        )
        return _obj
