# This file was auto-generated by Fern from our API Definition.

import datetime as dt
import typing
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.jsonable_encoder import jsonable_encoder
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.api_key_action_response import ApiKeyActionResponse
from ..types.api_key_create_response import ApiKeyCreateResponse
from ..types.api_key_list_response import ApiKeyListResponse
from ..types.api_key_response import ApiKeyResponse
from ..types.api_key_rotate_response import ApiKeyRotateResponse

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class RawApiKeysClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def list_api_keys(
        self,
        org_id: str,
        *,
        page: typing.Optional[int] = None,
        page_size: typing.Optional[int] = None,
        skip: typing.Optional[int] = None,
        take: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ApiKeyListResponse]:
        """
        List API keys for an organization.

        Supports both page/page_size and skip/take pagination styles.
        Returns empty list when no API keys exist.

        Args:
            org_id: Organization ID
            db: Database session
            auth: Authenticated user
            page: Page number (1-indexed, optional)
            page_size: Items per page (optional)
            skip: Number of items to skip (alternative to page)
            take: Number of items to take (alternative to page_size)

        Returns:
            Paginated list of API keys (empty list if none exist)

        Raises:
            ResourceNotFoundException: If organization not found
            AuthorizationException: If user is not a member

        Parameters
        ----------
        org_id : str

        page : typing.Optional[int]
            Page number (1-indexed)

        page_size : typing.Optional[int]
            Items per page

        skip : typing.Optional[int]
            Number of items to skip

        take : typing.Optional[int]
            Number of items to take

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ApiKeyListResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys",
            method="GET",
            params={
                "page": page,
                "page_size": page_size,
                "skip": skip,
                "take": take,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyListResponse,
                    parse_obj_as(
                        type_=ApiKeyListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def create_api_key(
        self,
        org_id: str,
        *,
        key_name: str,
        usage_limit_chf: typing.Optional[float] = OMIT,
        scopes: typing.Optional[typing.Sequence[str]] = OMIT,
        expires_at: typing.Optional[dt.datetime] = OMIT,
        metadata: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ApiKeyCreateResponse]:
        """
        Create a new API key for an organization.

        Requires admin or owner role.
        The raw API key is returned ONCE and must be stored securely by the client.

        Args:
            org_id: Organization ID
            request: API key creation request
            db: Database session
            auth: Authenticated user

        Returns:
            Created API key with raw key (shown ONCE only)

        Raises:
            ResourceNotFoundException: If organization not found
            AuthorizationException: If user lacks permissions
            ConflictException: If organization has reached max API keys
            ValidationException: If validation fails

        Parameters
        ----------
        org_id : str

        key_name : str
            Human-readable name for the API key

        usage_limit_chf : typing.Optional[float]
            Per-key monthly spending limit in CHF

        scopes : typing.Optional[typing.Sequence[str]]
            Permission scopes for the key

        expires_at : typing.Optional[dt.datetime]
            Optional expiration timestamp

        metadata : typing.Optional[typing.Dict[str, typing.Any]]
            Additional key metadata (e.g., deletable: false)

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ApiKeyCreateResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys",
            method="POST",
            json={
                "key_name": key_name,
                "usage_limit_chf": usage_limit_chf,
                "scopes": scopes,
                "expires_at": expires_at,
                "metadata": metadata,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyCreateResponse,
                    parse_obj_as(
                        type_=ApiKeyCreateResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get_api_key(
        self, org_id: str, key_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ApiKeyResponse]:
        """
        Get details of a specific API key.

        Requires organization membership.

        Args:
            org_id: Organization ID
            key_id: API key ID
            db: Database session
            auth: Authenticated user

        Returns:
            API key details

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user is not a member
            ValidationException: If key ID format is invalid

        Parameters
        ----------
        org_id : str

        key_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ApiKeyResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyResponse,
                    parse_obj_as(
                        type_=ApiKeyResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def delete_api_key(
        self, org_id: str, key_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ApiKeyActionResponse]:
        """
        Soft delete an API key (idempotent).

        Requires admin or owner role.

        Args:
            org_id: Organization ID
            key_id: API key ID
            db: Database session
            auth: Authenticated user

        Returns:
            Action result with deleted key info

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user lacks permissions

        Parameters
        ----------
        org_id : str

        key_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ApiKeyActionResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyActionResponse,
                    parse_obj_as(
                        type_=ApiKeyActionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def update_api_key(
        self,
        org_id: str,
        key_id: str,
        *,
        key_name: typing.Optional[str] = OMIT,
        usage_limit_chf: typing.Optional[float] = OMIT,
        scopes: typing.Optional[typing.Sequence[str]] = OMIT,
        expires_at: typing.Optional[dt.datetime] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ApiKeyResponse]:
        """
        Update API key metadata.

        Requires admin or owner role.
        Invalidates per-key limit cache when usage_limit_chf is updated.

        Args:
            org_id: Organization ID
            key_id: API key ID
            request: Update request
            db: Database session
            auth: Authenticated user

        Returns:
            Updated API key details

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user lacks permissions
            ValidationException: If validation fails

        Parameters
        ----------
        org_id : str

        key_id : str

        key_name : typing.Optional[str]
            New name for the API key

        usage_limit_chf : typing.Optional[float]
            New per-key monthly spending limit in CHF

        scopes : typing.Optional[typing.Sequence[str]]
            New permission scopes

        expires_at : typing.Optional[dt.datetime]
            New expiration timestamp

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ApiKeyResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}",
            method="PATCH",
            json={
                "key_name": key_name,
                "usage_limit_chf": usage_limit_chf,
                "scopes": scopes,
                "expires_at": expires_at,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyResponse,
                    parse_obj_as(
                        type_=ApiKeyResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def activate_api_key(
        self, org_id: str, key_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ApiKeyActionResponse]:
        """
        Activate an API key.

        Requires admin or owner role.

        Args:
            org_id: Organization ID
            key_id: API key ID
            db: Database session
            auth: Authenticated user

        Returns:
            Action result with updated key

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user lacks permissions

        Parameters
        ----------
        org_id : str

        key_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ApiKeyActionResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}/activate",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyActionResponse,
                    parse_obj_as(
                        type_=ApiKeyActionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def deactivate_api_key(
        self, org_id: str, key_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ApiKeyActionResponse]:
        """
        Deactivate an API key.

        Requires admin or owner role.

        Args:
            org_id: Organization ID
            key_id: API key ID
            db: Database session
            auth: Authenticated user

        Returns:
            Action result with updated key

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user lacks permissions

        Parameters
        ----------
        org_id : str

        key_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ApiKeyActionResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}/deactivate",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyActionResponse,
                    parse_obj_as(
                        type_=ApiKeyActionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def pause_api_key(
        self, org_id: str, key_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ApiKeyActionResponse]:
        """
        Pause an API key temporarily.

        Requires admin or owner role.

        Args:
            org_id: Organization ID
            key_id: API key ID
            db: Database session
            auth: Authenticated user

        Returns:
            Action result with updated key

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user lacks permissions

        Parameters
        ----------
        org_id : str

        key_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ApiKeyActionResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}/pause",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyActionResponse,
                    parse_obj_as(
                        type_=ApiKeyActionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def unpause_api_key(
        self, org_id: str, key_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ApiKeyActionResponse]:
        """
        Unpause an API key.

        Requires admin or owner role.

        Args:
            org_id: Organization ID
            key_id: API key ID
            db: Database session
            auth: Authenticated user

        Returns:
            Action result with updated key

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user lacks permissions

        Parameters
        ----------
        org_id : str

        key_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ApiKeyActionResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}/unpause",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyActionResponse,
                    parse_obj_as(
                        type_=ApiKeyActionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def rotate_api_key(
        self, org_id: str, key_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ApiKeyRotateResponse]:
        """
        Rotate an API key (delete old, create new with same settings).

        Requires admin or owner role.
        The new raw API key is returned ONCE and must be stored securely.

        Args:
            org_id: Organization ID
            key_id: API key ID to rotate
            db: Database session
            auth: Authenticated user

        Returns:
            Rotation result with new key (raw key shown ONCE only)

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user lacks permissions
            ConflictException: If key is already deleted

        Parameters
        ----------
        org_id : str

        key_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ApiKeyRotateResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}/rotate",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyRotateResponse,
                    parse_obj_as(
                        type_=ApiKeyRotateResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawApiKeysClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list_api_keys(
        self,
        org_id: str,
        *,
        page: typing.Optional[int] = None,
        page_size: typing.Optional[int] = None,
        skip: typing.Optional[int] = None,
        take: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ApiKeyListResponse]:
        """
        List API keys for an organization.

        Supports both page/page_size and skip/take pagination styles.
        Returns empty list when no API keys exist.

        Args:
            org_id: Organization ID
            db: Database session
            auth: Authenticated user
            page: Page number (1-indexed, optional)
            page_size: Items per page (optional)
            skip: Number of items to skip (alternative to page)
            take: Number of items to take (alternative to page_size)

        Returns:
            Paginated list of API keys (empty list if none exist)

        Raises:
            ResourceNotFoundException: If organization not found
            AuthorizationException: If user is not a member

        Parameters
        ----------
        org_id : str

        page : typing.Optional[int]
            Page number (1-indexed)

        page_size : typing.Optional[int]
            Items per page

        skip : typing.Optional[int]
            Number of items to skip

        take : typing.Optional[int]
            Number of items to take

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ApiKeyListResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys",
            method="GET",
            params={
                "page": page,
                "page_size": page_size,
                "skip": skip,
                "take": take,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyListResponse,
                    parse_obj_as(
                        type_=ApiKeyListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def create_api_key(
        self,
        org_id: str,
        *,
        key_name: str,
        usage_limit_chf: typing.Optional[float] = OMIT,
        scopes: typing.Optional[typing.Sequence[str]] = OMIT,
        expires_at: typing.Optional[dt.datetime] = OMIT,
        metadata: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ApiKeyCreateResponse]:
        """
        Create a new API key for an organization.

        Requires admin or owner role.
        The raw API key is returned ONCE and must be stored securely by the client.

        Args:
            org_id: Organization ID
            request: API key creation request
            db: Database session
            auth: Authenticated user

        Returns:
            Created API key with raw key (shown ONCE only)

        Raises:
            ResourceNotFoundException: If organization not found
            AuthorizationException: If user lacks permissions
            ConflictException: If organization has reached max API keys
            ValidationException: If validation fails

        Parameters
        ----------
        org_id : str

        key_name : str
            Human-readable name for the API key

        usage_limit_chf : typing.Optional[float]
            Per-key monthly spending limit in CHF

        scopes : typing.Optional[typing.Sequence[str]]
            Permission scopes for the key

        expires_at : typing.Optional[dt.datetime]
            Optional expiration timestamp

        metadata : typing.Optional[typing.Dict[str, typing.Any]]
            Additional key metadata (e.g., deletable: false)

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ApiKeyCreateResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys",
            method="POST",
            json={
                "key_name": key_name,
                "usage_limit_chf": usage_limit_chf,
                "scopes": scopes,
                "expires_at": expires_at,
                "metadata": metadata,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyCreateResponse,
                    parse_obj_as(
                        type_=ApiKeyCreateResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get_api_key(
        self, org_id: str, key_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ApiKeyResponse]:
        """
        Get details of a specific API key.

        Requires organization membership.

        Args:
            org_id: Organization ID
            key_id: API key ID
            db: Database session
            auth: Authenticated user

        Returns:
            API key details

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user is not a member
            ValidationException: If key ID format is invalid

        Parameters
        ----------
        org_id : str

        key_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ApiKeyResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyResponse,
                    parse_obj_as(
                        type_=ApiKeyResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def delete_api_key(
        self, org_id: str, key_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ApiKeyActionResponse]:
        """
        Soft delete an API key (idempotent).

        Requires admin or owner role.

        Args:
            org_id: Organization ID
            key_id: API key ID
            db: Database session
            auth: Authenticated user

        Returns:
            Action result with deleted key info

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user lacks permissions

        Parameters
        ----------
        org_id : str

        key_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ApiKeyActionResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyActionResponse,
                    parse_obj_as(
                        type_=ApiKeyActionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def update_api_key(
        self,
        org_id: str,
        key_id: str,
        *,
        key_name: typing.Optional[str] = OMIT,
        usage_limit_chf: typing.Optional[float] = OMIT,
        scopes: typing.Optional[typing.Sequence[str]] = OMIT,
        expires_at: typing.Optional[dt.datetime] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ApiKeyResponse]:
        """
        Update API key metadata.

        Requires admin or owner role.
        Invalidates per-key limit cache when usage_limit_chf is updated.

        Args:
            org_id: Organization ID
            key_id: API key ID
            request: Update request
            db: Database session
            auth: Authenticated user

        Returns:
            Updated API key details

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user lacks permissions
            ValidationException: If validation fails

        Parameters
        ----------
        org_id : str

        key_id : str

        key_name : typing.Optional[str]
            New name for the API key

        usage_limit_chf : typing.Optional[float]
            New per-key monthly spending limit in CHF

        scopes : typing.Optional[typing.Sequence[str]]
            New permission scopes

        expires_at : typing.Optional[dt.datetime]
            New expiration timestamp

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ApiKeyResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}",
            method="PATCH",
            json={
                "key_name": key_name,
                "usage_limit_chf": usage_limit_chf,
                "scopes": scopes,
                "expires_at": expires_at,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyResponse,
                    parse_obj_as(
                        type_=ApiKeyResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def activate_api_key(
        self, org_id: str, key_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ApiKeyActionResponse]:
        """
        Activate an API key.

        Requires admin or owner role.

        Args:
            org_id: Organization ID
            key_id: API key ID
            db: Database session
            auth: Authenticated user

        Returns:
            Action result with updated key

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user lacks permissions

        Parameters
        ----------
        org_id : str

        key_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ApiKeyActionResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}/activate",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyActionResponse,
                    parse_obj_as(
                        type_=ApiKeyActionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def deactivate_api_key(
        self, org_id: str, key_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ApiKeyActionResponse]:
        """
        Deactivate an API key.

        Requires admin or owner role.

        Args:
            org_id: Organization ID
            key_id: API key ID
            db: Database session
            auth: Authenticated user

        Returns:
            Action result with updated key

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user lacks permissions

        Parameters
        ----------
        org_id : str

        key_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ApiKeyActionResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}/deactivate",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyActionResponse,
                    parse_obj_as(
                        type_=ApiKeyActionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def pause_api_key(
        self, org_id: str, key_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ApiKeyActionResponse]:
        """
        Pause an API key temporarily.

        Requires admin or owner role.

        Args:
            org_id: Organization ID
            key_id: API key ID
            db: Database session
            auth: Authenticated user

        Returns:
            Action result with updated key

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user lacks permissions

        Parameters
        ----------
        org_id : str

        key_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ApiKeyActionResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}/pause",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyActionResponse,
                    parse_obj_as(
                        type_=ApiKeyActionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def unpause_api_key(
        self, org_id: str, key_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ApiKeyActionResponse]:
        """
        Unpause an API key.

        Requires admin or owner role.

        Args:
            org_id: Organization ID
            key_id: API key ID
            db: Database session
            auth: Authenticated user

        Returns:
            Action result with updated key

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user lacks permissions

        Parameters
        ----------
        org_id : str

        key_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ApiKeyActionResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}/unpause",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyActionResponse,
                    parse_obj_as(
                        type_=ApiKeyActionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def rotate_api_key(
        self, org_id: str, key_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ApiKeyRotateResponse]:
        """
        Rotate an API key (delete old, create new with same settings).

        Requires admin or owner role.
        The new raw API key is returned ONCE and must be stored securely.

        Args:
            org_id: Organization ID
            key_id: API key ID to rotate
            db: Database session
            auth: Authenticated user

        Returns:
            Rotation result with new key (raw key shown ONCE only)

        Raises:
            ResourceNotFoundException: If organization or key not found
            AuthorizationException: If user lacks permissions
            ConflictException: If key is already deleted

        Parameters
        ----------
        org_id : str

        key_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ApiKeyRotateResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(org_id)}/api-keys/{jsonable_encoder(key_id)}/rotate",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyRotateResponse,
                    parse_obj_as(
                        type_=ApiKeyRotateResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
