# This file is auto-generated by oagen. Do not edit.

from __future__ import annotations

from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union

if TYPE_CHECKING:
    from .._client import AsyncWorkOSClient, WorkOSClient

from .._types import RequestOptions, enum_value, NOT_GIVEN, NotGiven
from .models import (
    ApiKey,
    ApiKeyValidationResponse,
    OrganizationApiKey,
    OrganizationApiKeyWithValue,
)
from workos.common.models.pagination_order import PaginationOrder
from .._pagination import AsyncPage, SyncPage


class ApiKeys:
    """Api Keys API resources."""

    def __init__(self, client: "WorkOSClient") -> None:
        self._client = client

    def list_organization_api_keys(
        self,
        organization_id: str,
        *,
        limit: Optional[int] = None,
        before: Optional[str] = None,
        after: Optional[str] = None,
        order: Optional[Union[PaginationOrder, str]] = "desc",
        request_options: Optional[RequestOptions] = None,
    ) -> SyncPage[OrganizationApiKey]:
        """List API keys for an organization

        Get a list of all API keys for an organization.

        Args:
            organization_id: Unique identifier of the Organization.
            limit: Upper limit on the number of objects to return, between `1` and `100`. Defaults to `10`.
            before: An object ID that defines your place in the list. When the ID is not present, you are at the end of the list.
            after: An object ID that defines your place in the list. When the ID is not present, you are at the end of the list.
            order: Order the results by the creation time. Defaults to `desc`.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            SyncPage[OrganizationApiKey]

        Raises:
            NotFoundError: If the resource is not found (404).
            AuthenticationError: If the API key is invalid (401).
            RateLimitExceededError: If rate limited (429).
            ServerError: If the server returns a 5xx error.
        """
        params = {
            k: v
            for k, v in {
                "limit": limit,
                "before": before,
                "after": after,
                "order": enum_value(order) if order is not None else None,
            }.items()
            if v is not None
        }
        return self._client.request_page(
            method="get",
            path=("organizations", str(organization_id), "api_keys"),
            model=OrganizationApiKey,
            params=params,
            request_options=request_options,
        )

    def create_organization_api_key(
        self,
        organization_id: str,
        *,
        name: str,
        permissions: Optional[List[str]] = None,
        expires_at: Optional[str] = None,
        request_options: Optional[RequestOptions] = None,
    ) -> OrganizationApiKeyWithValue:
        """Create an API key for an organization

        Create a new API key for an organization.

        Args:
            organization_id: Unique identifier of the Organization.
            name: The name for the API key.
            permissions: The permission slugs to assign to the API key.
            expires_at: The timestamp when the API key should expire. Must be a future timestamp. If omitted, the key does not expire.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            OrganizationApiKeyWithValue

        Raises:
            NotFoundError: If the resource is not found (404).
            UnprocessableEntityError: If the request data is unprocessable (422).
            AuthenticationError: If the API key is invalid (401).
            RateLimitExceededError: If rate limited (429).
            ServerError: If the server returns a 5xx error.
        """
        body: Dict[str, Any] = {
            k: v
            for k, v in {
                "name": name,
                "permissions": permissions,
                "expires_at": expires_at,
            }.items()
            if v is not None
        }
        return self._client.request(
            method="post",
            path=("organizations", str(organization_id), "api_keys"),
            body=body,
            model=OrganizationApiKeyWithValue,
            request_options=request_options,
        )

    def create_validation(
        self,
        *,
        value: str,
        request_options: Optional[RequestOptions] = None,
    ) -> ApiKeyValidationResponse:
        """Validate API key

        Validate an API key value and return the API key object if valid.

        Args:
            value: The value for an API key.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            ApiKeyValidationResponse

        Raises:
            AuthenticationError: If the API key is invalid (401).
            UnprocessableEntityError: If the request data is unprocessable (422).
            RateLimitExceededError: If rate limited (429).
            ServerError: If the server returns a 5xx error.
        """
        body: Dict[str, Any] = {
            "value": value,
        }
        return self._client.request(
            method="post",
            path=("api_keys", "validations"),
            body=body,
            model=ApiKeyValidationResponse,
            request_options=request_options,
        )

    def delete_api_key(
        self,
        id: str,
        *,
        request_options: Optional[RequestOptions] = None,
    ) -> None:
        """Delete an API key

        Permanently deletes an API key. This action cannot be undone. Once deleted, any requests using this API key will fail authentication.

        Args:
            id: The unique ID of the API key.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Raises:
            NotFoundError: If the resource is not found (404).
            AuthenticationError: If the API key is invalid (401).
            RateLimitExceededError: If rate limited (429).
            ServerError: If the server returns a 5xx error.
        """
        self._client.request(
            method="delete",
            path=("api_keys", str(id)),
            request_options=request_options,
        )

    def create_api_key_expire(
        self,
        id: str,
        *,
        expires_at: Union[str, None, NotGiven] = NOT_GIVEN,
        request_options: Optional[RequestOptions] = None,
    ) -> ApiKey:
        """Expire an API key

        Expire an API key immediately, schedule a future expiration, or clear a scheduled future expiration.

        Args:
            id: The unique ID of the API key.
            expires_at: When the API key should expire. If omitted or in the past, the key expires immediately. Use null to clear a scheduled future expiration.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            ApiKey

        Raises:
            NotFoundError: If the resource is not found (404).
            ConflictError: If a conflict occurs (409).
            UnprocessableEntityError: If the request data is unprocessable (422).
            AuthenticationError: If the API key is invalid (401).
            RateLimitExceededError: If rate limited (429).
            ServerError: If the server returns a 5xx error.
        """
        body: Dict[str, Any] = {}
        if not isinstance(expires_at, NotGiven):
            body["expires_at"] = expires_at
        return self._client.request(
            method="post",
            path=("api_keys", str(id), "expire"),
            body=body,
            model=ApiKey,
            request_options=request_options,
        )


class AsyncApiKeys:
    """Api Keys API resources (async)."""

    def __init__(self, client: "AsyncWorkOSClient") -> None:
        self._client = client

    async def list_organization_api_keys(
        self,
        organization_id: str,
        *,
        limit: Optional[int] = None,
        before: Optional[str] = None,
        after: Optional[str] = None,
        order: Optional[Union[PaginationOrder, str]] = "desc",
        request_options: Optional[RequestOptions] = None,
    ) -> AsyncPage[OrganizationApiKey]:
        """List API keys for an organization

        Get a list of all API keys for an organization.

        Args:
            organization_id: Unique identifier of the Organization.
            limit: Upper limit on the number of objects to return, between `1` and `100`. Defaults to `10`.
            before: An object ID that defines your place in the list. When the ID is not present, you are at the end of the list.
            after: An object ID that defines your place in the list. When the ID is not present, you are at the end of the list.
            order: Order the results by the creation time. Defaults to `desc`.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            AsyncPage[OrganizationApiKey]

        Raises:
            NotFoundError: If the resource is not found (404).
            AuthenticationError: If the API key is invalid (401).
            RateLimitExceededError: If rate limited (429).
            ServerError: If the server returns a 5xx error.
        """
        params = {
            k: v
            for k, v in {
                "limit": limit,
                "before": before,
                "after": after,
                "order": enum_value(order) if order is not None else None,
            }.items()
            if v is not None
        }
        return await self._client.request_page(
            method="get",
            path=("organizations", str(organization_id), "api_keys"),
            model=OrganizationApiKey,
            params=params,
            request_options=request_options,
        )

    async def create_organization_api_key(
        self,
        organization_id: str,
        *,
        name: str,
        permissions: Optional[List[str]] = None,
        expires_at: Optional[str] = None,
        request_options: Optional[RequestOptions] = None,
    ) -> OrganizationApiKeyWithValue:
        """Create an API key for an organization

        Create a new API key for an organization.

        Args:
            organization_id: Unique identifier of the Organization.
            name: The name for the API key.
            permissions: The permission slugs to assign to the API key.
            expires_at: The timestamp when the API key should expire. Must be a future timestamp. If omitted, the key does not expire.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            OrganizationApiKeyWithValue

        Raises:
            NotFoundError: If the resource is not found (404).
            UnprocessableEntityError: If the request data is unprocessable (422).
            AuthenticationError: If the API key is invalid (401).
            RateLimitExceededError: If rate limited (429).
            ServerError: If the server returns a 5xx error.
        """
        body: Dict[str, Any] = {
            k: v
            for k, v in {
                "name": name,
                "permissions": permissions,
                "expires_at": expires_at,
            }.items()
            if v is not None
        }
        return await self._client.request(
            method="post",
            path=("organizations", str(organization_id), "api_keys"),
            body=body,
            model=OrganizationApiKeyWithValue,
            request_options=request_options,
        )

    async def create_validation(
        self,
        *,
        value: str,
        request_options: Optional[RequestOptions] = None,
    ) -> ApiKeyValidationResponse:
        """Validate API key

        Validate an API key value and return the API key object if valid.

        Args:
            value: The value for an API key.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            ApiKeyValidationResponse

        Raises:
            AuthenticationError: If the API key is invalid (401).
            UnprocessableEntityError: If the request data is unprocessable (422).
            RateLimitExceededError: If rate limited (429).
            ServerError: If the server returns a 5xx error.
        """
        body: Dict[str, Any] = {
            "value": value,
        }
        return await self._client.request(
            method="post",
            path=("api_keys", "validations"),
            body=body,
            model=ApiKeyValidationResponse,
            request_options=request_options,
        )

    async def delete_api_key(
        self,
        id: str,
        *,
        request_options: Optional[RequestOptions] = None,
    ) -> None:
        """Delete an API key

        Permanently deletes an API key. This action cannot be undone. Once deleted, any requests using this API key will fail authentication.

        Args:
            id: The unique ID of the API key.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Raises:
            NotFoundError: If the resource is not found (404).
            AuthenticationError: If the API key is invalid (401).
            RateLimitExceededError: If rate limited (429).
            ServerError: If the server returns a 5xx error.
        """
        await self._client.request(
            method="delete",
            path=("api_keys", str(id)),
            request_options=request_options,
        )

    async def create_api_key_expire(
        self,
        id: str,
        *,
        expires_at: Union[str, None, NotGiven] = NOT_GIVEN,
        request_options: Optional[RequestOptions] = None,
    ) -> ApiKey:
        """Expire an API key

        Expire an API key immediately, schedule a future expiration, or clear a scheduled future expiration.

        Args:
            id: The unique ID of the API key.
            expires_at: When the API key should expire. If omitted or in the past, the key expires immediately. Use null to clear a scheduled future expiration.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            ApiKey

        Raises:
            NotFoundError: If the resource is not found (404).
            ConflictError: If a conflict occurs (409).
            UnprocessableEntityError: If the request data is unprocessable (422).
            AuthenticationError: If the API key is invalid (401).
            RateLimitExceededError: If rate limited (429).
            ServerError: If the server returns a 5xx error.
        """
        body: Dict[str, Any] = {}
        if not isinstance(expires_at, NotGiven):
            body["expires_at"] = expires_at
        return await self._client.request(
            method="post",
            path=("api_keys", str(id), "expire"),
            body=body,
            model=ApiKey,
            request_options=request_options,
        )
