"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""

from __future__ import annotations
from .keycreditsdata import KeyCreditsData, KeyCreditsDataTypedDict
from .ratelimitrequest import RatelimitRequest, RatelimitRequestTypedDict
import pydantic
from pydantic import model_serializer
from typing import Any, Dict, List, Optional
from typing_extensions import Annotated, NotRequired, TypedDict
from unkey.py.types import BaseModel, Nullable, OptionalNullable, UNSET, UNSET_SENTINEL


class V2KeysUpdateKeyRequestBodyTypedDict(TypedDict):
    key_id: str
    r"""Specifies which key to update using the database identifier returned from `createKey`.
    Do not confuse this with the actual API key string that users include in requests.

    """
    name: NotRequired[Nullable[str]]
    r"""Sets a human-readable name for internal organization and identification.
    Omitting this field leaves the current name unchanged, while setting null removes it entirely.
    Avoid generic names like \"API Key\" when managing multiple keys per user or service.

    """
    external_id: NotRequired[Nullable[str]]
    r"""Links this key to a user or entity in your system for ownership tracking during verification.
    Omitting this field preserves the current association, while setting null disconnects the key from any identity.
    Essential for user-specific analytics, billing, and key management across multiple users.
    Supports letters, numbers, underscores, dots, and hyphens for flexible identifier formats.

    """
    meta: NotRequired[Nullable[Dict[str, Any]]]
    r"""Stores arbitrary JSON metadata returned during key verification.
    Omitting this field preserves existing metadata, while setting null removes all metadata entirely.
    Avoid storing sensitive data here as it's returned in verification responses.
    Large metadata objects increase verification latency and should stay under 10KB total size.

    """
    expires: NotRequired[Nullable[int]]
    r"""Sets when this key automatically expires as a Unix timestamp in milliseconds.
    Verification fails with code=EXPIRED immediately after this time passes.
    Omitting this field preserves the current expiration, while setting null makes the key permanent.

    Avoid setting timestamps in the past as they immediately invalidate the key.
    Keys expire based on server time, not client time, which prevents timezone-related issues.
    Active sessions continue until their next verification attempt after expiry.

    """
    credits: NotRequired[KeyCreditsDataTypedDict]
    r"""Credit configuration and remaining balance for this key."""
    ratelimits: NotRequired[List[RatelimitRequestTypedDict]]
    r"""Defines time-based rate limits that protect against abuse by controlling request frequency.
    Omitting this field preserves existing rate limits, while setting null removes all rate limits.
    Unlike credits which track total usage, rate limits reset automatically after each window expires.
    Multiple rate limits can control different operation types with separate thresholds and windows.

    """
    enabled: NotRequired[bool]
    r"""Controls whether the key is currently active for verification requests.
    When set to `false`, all verification attempts fail with `code=DISABLED` regardless of other settings.
    Omitting this field preserves the current enabled status.
    Useful for temporarily suspending access during billing issues, security incidents, or maintenance windows without losing key configuration.

    """
    roles: NotRequired[List[str]]
    permissions: NotRequired[List[str]]


class V2KeysUpdateKeyRequestBody(BaseModel):
    key_id: Annotated[str, pydantic.Field(alias="keyId")]
    r"""Specifies which key to update using the database identifier returned from `createKey`.
    Do not confuse this with the actual API key string that users include in requests.

    """

    name: OptionalNullable[str] = UNSET
    r"""Sets a human-readable name for internal organization and identification.
    Omitting this field leaves the current name unchanged, while setting null removes it entirely.
    Avoid generic names like \"API Key\" when managing multiple keys per user or service.

    """

    external_id: Annotated[
        OptionalNullable[str], pydantic.Field(alias="externalId")
    ] = UNSET
    r"""Links this key to a user or entity in your system for ownership tracking during verification.
    Omitting this field preserves the current association, while setting null disconnects the key from any identity.
    Essential for user-specific analytics, billing, and key management across multiple users.
    Supports letters, numbers, underscores, dots, and hyphens for flexible identifier formats.

    """

    meta: OptionalNullable[Dict[str, Any]] = UNSET
    r"""Stores arbitrary JSON metadata returned during key verification.
    Omitting this field preserves existing metadata, while setting null removes all metadata entirely.
    Avoid storing sensitive data here as it's returned in verification responses.
    Large metadata objects increase verification latency and should stay under 10KB total size.

    """

    expires: OptionalNullable[int] = UNSET
    r"""Sets when this key automatically expires as a Unix timestamp in milliseconds.
    Verification fails with code=EXPIRED immediately after this time passes.
    Omitting this field preserves the current expiration, while setting null makes the key permanent.

    Avoid setting timestamps in the past as they immediately invalidate the key.
    Keys expire based on server time, not client time, which prevents timezone-related issues.
    Active sessions continue until their next verification attempt after expiry.

    """

    credits: Optional[KeyCreditsData] = None
    r"""Credit configuration and remaining balance for this key."""

    ratelimits: Optional[List[RatelimitRequest]] = None
    r"""Defines time-based rate limits that protect against abuse by controlling request frequency.
    Omitting this field preserves existing rate limits, while setting null removes all rate limits.
    Unlike credits which track total usage, rate limits reset automatically after each window expires.
    Multiple rate limits can control different operation types with separate thresholds and windows.

    """

    enabled: Optional[bool] = None
    r"""Controls whether the key is currently active for verification requests.
    When set to `false`, all verification attempts fail with `code=DISABLED` regardless of other settings.
    Omitting this field preserves the current enabled status.
    Useful for temporarily suspending access during billing issues, security incidents, or maintenance windows without losing key configuration.

    """

    roles: Optional[List[str]] = None

    permissions: Optional[List[str]] = None

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = [
            "name",
            "externalId",
            "meta",
            "expires",
            "credits",
            "ratelimits",
            "enabled",
            "roles",
            "permissions",
        ]
        nullable_fields = ["name", "externalId", "meta", "expires"]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m
