# 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
from .models import (
    AuditLogAction,
    AuditLogEvent,
    AuditLogEventCreateResponse,
    AuditLogExport,
    AuditLogSchema,
    AuditLogSchemaActorInput,
    AuditLogSchemaTargetInput,
)
from workos.organizations.models.audit_logs_retention import AuditLogsRetention
from workos.common.models.pagination_order import PaginationOrder
from .._pagination import AsyncPage, SyncPage


class AuditLogs:
    """Audit Logs API resources."""

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

    def get_organization_audit_logs_retention(
        self,
        id: str,
        *,
        request_options: Optional[RequestOptions] = None,
    ) -> AuditLogsRetention:
        """Get Retention

        Get the configured event retention period for the given Organization.

        Args:
            id: Unique identifier of the Organization.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            AuditLogsRetention

        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.
        """
        return self._client.request(
            method="get",
            path=("organizations", str(id), "audit_logs_retention"),
            model=AuditLogsRetention,
            request_options=request_options,
        )

    def update_organization_audit_logs_retention(
        self,
        id: str,
        *,
        retention_period_in_days: int,
        request_options: Optional[RequestOptions] = None,
    ) -> AuditLogsRetention:
        """Set Retention

        Set the event retention period for the given Organization.

        Args:
            id: Unique identifier of the Organization.
            retention_period_in_days: The number of days Audit Log events will be retained. Valid values are `30` and `365`.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            AuditLogsRetention

        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] = {
            "retention_period_in_days": retention_period_in_days,
        }
        return self._client.request(
            method="put",
            path=("organizations", str(id), "audit_logs_retention"),
            body=body,
            model=AuditLogsRetention,
            request_options=request_options,
        )

    def list_actions(
        self,
        *,
        limit: Optional[int] = None,
        before: Optional[str] = None,
        after: Optional[str] = None,
        order: Optional[Union[PaginationOrder, str]] = "desc",
        request_options: Optional[RequestOptions] = None,
    ) -> SyncPage[AuditLogAction]:
        """List Actions

        Get a list of all Audit Log actions in the current environment.

        Args:
            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[AuditLogAction]

        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.
        """
        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=("audit_logs", "actions"),
            model=AuditLogAction,
            params=params,
            request_options=request_options,
        )

    def list_action_schemas(
        self,
        action_name: 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[AuditLogSchema]:
        """List Schemas

        Get a list of all schemas for the Audit Logs action identified by `:name`.

        Args:
            action_name: The name of the Audit Log action.
            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[AuditLogSchema]

        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.
        """
        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=("audit_logs", "actions", str(action_name), "schemas"),
            model=AuditLogSchema,
            params=params,
            request_options=request_options,
        )

    def create_schema(
        self,
        action_name: str,
        *,
        targets: List[AuditLogSchemaTargetInput],
        actor: Optional[AuditLogSchemaActorInput] = None,
        metadata: Optional[Dict[str, Any]] = None,
        request_options: Optional[RequestOptions] = None,
    ) -> AuditLogSchema:
        """Create Schema

        Creates a new Audit Log schema used to validate the payload of incoming Audit Log Events. If the `action` does not exist, it will also be created.

        Args:
            action_name: The name of the Audit Log action.
            actor: The metadata schema for the actor.
            targets: The list of targets for the schema.
            metadata: Optional JSON schema for event metadata.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            AuditLogSchema

        Raises:
            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 {
                "actor": actor.to_dict() if actor is not None else None,
                "targets": [item.to_dict() for item in targets],
                "metadata": metadata,
            }.items()
            if v is not None
        }
        return self._client.request(
            method="post",
            path=("audit_logs", "actions", str(action_name), "schemas"),
            body=body,
            model=AuditLogSchema,
            request_options=request_options,
        )

    def create_event(
        self,
        *,
        organization_id: str,
        event: AuditLogEvent,
        idempotency_key: Optional[str] = None,
        request_options: Optional[RequestOptions] = None,
    ) -> AuditLogEventCreateResponse:
        """Create Event

        Create an Audit Log Event.

        This API supports idempotency which guarantees that performing the same operation multiple times will have the same result as if the operation were performed only once. This is handy in situations where you may need to retry a request due to a failure or prevent accidental duplicate requests from creating more than one resource.

        To achieve idempotency, you can add `Idempotency-Key` request header to a Create Event request with a unique string as the value. Each subsequent request matching this unique string will return the same response. We suggest using [v4 UUIDs](https://en.wikipedia.org/wiki/Universally_unique_identifier) for idempotency keys to avoid collisions.

        Idempotency keys expire after 24 hours. The API will generate a new response if you submit a request with an expired key.

        Args:
            organization_id: The unique ID of the Organization.
            event: The audit log event to create.
            idempotency_key: Optional idempotency key for safe retries.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            AuditLogEventCreateResponse

        Raises:
            BadRequestError: If the request is malformed (400).
            NotFoundError: If the resource is not found (404).
            UnprocessableEntityError: If the request data is unprocessable (422).
            RateLimitExceededError: If rate limited (429).
            AuthenticationError: If the API key is invalid (401).
            ServerError: If the server returns a 5xx error.
        """
        body: Dict[str, Any] = {
            "organization_id": organization_id,
            "event": event.to_dict(),
        }
        return self._client.request(
            method="post",
            path=("audit_logs", "events"),
            body=body,
            model=AuditLogEventCreateResponse,
            idempotency_key=idempotency_key,
            request_options=request_options,
        )

    def create_export(
        self,
        *,
        organization_id: str,
        range_start: str,
        range_end: str,
        actions: Optional[List[str]] = None,
        actors: Optional[List[str]] = None,
        actor_names: Optional[List[str]] = None,
        actor_ids: Optional[List[str]] = None,
        targets: Optional[List[str]] = None,
        request_options: Optional[RequestOptions] = None,
    ) -> AuditLogExport:
        """Create Export

        Create an Audit Log Export. Exports are scoped to a single organization within a specified date range.

        Args:
            organization_id: The unique ID of the Organization.
            range_start: ISO-8601 value for start of the export range.
            range_end: ISO-8601 value for end of the export range.
            actions: List of actions to filter against.
            actors: (deprecated) Deprecated. Use `actor_names` instead.
            actor_names: List of actor names to filter against.
            actor_ids: List of actor IDs to filter against.
            targets: List of target types to filter against.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            AuditLogExport

        Raises:
            BadRequestError: If the request is malformed (400).
            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 {
                "organization_id": organization_id,
                "range_start": range_start,
                "range_end": range_end,
                "actions": actions,
                "actors": actors,
                "actor_names": actor_names,
                "actor_ids": actor_ids,
                "targets": targets,
            }.items()
            if v is not None
        }
        return self._client.request(
            method="post",
            path=("audit_logs", "exports"),
            body=body,
            model=AuditLogExport,
            request_options=request_options,
        )

    def get_export(
        self,
        audit_log_export_id: str,
        *,
        request_options: Optional[RequestOptions] = None,
    ) -> AuditLogExport:
        """Get Export

        Get an Audit Log Export. The URL will expire after 10 minutes. If the export is needed again at a later time, refetching the export will regenerate the URL.

        Args:
            audit_log_export_id: The unique ID of the Audit Log Export.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            AuditLogExport

        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.
        """
        return self._client.request(
            method="get",
            path=("audit_logs", "exports", str(audit_log_export_id)),
            model=AuditLogExport,
            request_options=request_options,
        )


class AsyncAuditLogs:
    """Audit Logs API resources (async)."""

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

    async def get_organization_audit_logs_retention(
        self,
        id: str,
        *,
        request_options: Optional[RequestOptions] = None,
    ) -> AuditLogsRetention:
        """Get Retention

        Get the configured event retention period for the given Organization.

        Args:
            id: Unique identifier of the Organization.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            AuditLogsRetention

        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.
        """
        return await self._client.request(
            method="get",
            path=("organizations", str(id), "audit_logs_retention"),
            model=AuditLogsRetention,
            request_options=request_options,
        )

    async def update_organization_audit_logs_retention(
        self,
        id: str,
        *,
        retention_period_in_days: int,
        request_options: Optional[RequestOptions] = None,
    ) -> AuditLogsRetention:
        """Set Retention

        Set the event retention period for the given Organization.

        Args:
            id: Unique identifier of the Organization.
            retention_period_in_days: The number of days Audit Log events will be retained. Valid values are `30` and `365`.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            AuditLogsRetention

        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] = {
            "retention_period_in_days": retention_period_in_days,
        }
        return await self._client.request(
            method="put",
            path=("organizations", str(id), "audit_logs_retention"),
            body=body,
            model=AuditLogsRetention,
            request_options=request_options,
        )

    async def list_actions(
        self,
        *,
        limit: Optional[int] = None,
        before: Optional[str] = None,
        after: Optional[str] = None,
        order: Optional[Union[PaginationOrder, str]] = "desc",
        request_options: Optional[RequestOptions] = None,
    ) -> AsyncPage[AuditLogAction]:
        """List Actions

        Get a list of all Audit Log actions in the current environment.

        Args:
            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[AuditLogAction]

        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.
        """
        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=("audit_logs", "actions"),
            model=AuditLogAction,
            params=params,
            request_options=request_options,
        )

    async def list_action_schemas(
        self,
        action_name: 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[AuditLogSchema]:
        """List Schemas

        Get a list of all schemas for the Audit Logs action identified by `:name`.

        Args:
            action_name: The name of the Audit Log action.
            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[AuditLogSchema]

        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.
        """
        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=("audit_logs", "actions", str(action_name), "schemas"),
            model=AuditLogSchema,
            params=params,
            request_options=request_options,
        )

    async def create_schema(
        self,
        action_name: str,
        *,
        targets: List[AuditLogSchemaTargetInput],
        actor: Optional[AuditLogSchemaActorInput] = None,
        metadata: Optional[Dict[str, Any]] = None,
        request_options: Optional[RequestOptions] = None,
    ) -> AuditLogSchema:
        """Create Schema

        Creates a new Audit Log schema used to validate the payload of incoming Audit Log Events. If the `action` does not exist, it will also be created.

        Args:
            action_name: The name of the Audit Log action.
            actor: The metadata schema for the actor.
            targets: The list of targets for the schema.
            metadata: Optional JSON schema for event metadata.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            AuditLogSchema

        Raises:
            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 {
                "actor": actor.to_dict() if actor is not None else None,
                "targets": [item.to_dict() for item in targets],
                "metadata": metadata,
            }.items()
            if v is not None
        }
        return await self._client.request(
            method="post",
            path=("audit_logs", "actions", str(action_name), "schemas"),
            body=body,
            model=AuditLogSchema,
            request_options=request_options,
        )

    async def create_event(
        self,
        *,
        organization_id: str,
        event: AuditLogEvent,
        idempotency_key: Optional[str] = None,
        request_options: Optional[RequestOptions] = None,
    ) -> AuditLogEventCreateResponse:
        """Create Event

        Create an Audit Log Event.

        This API supports idempotency which guarantees that performing the same operation multiple times will have the same result as if the operation were performed only once. This is handy in situations where you may need to retry a request due to a failure or prevent accidental duplicate requests from creating more than one resource.

        To achieve idempotency, you can add `Idempotency-Key` request header to a Create Event request with a unique string as the value. Each subsequent request matching this unique string will return the same response. We suggest using [v4 UUIDs](https://en.wikipedia.org/wiki/Universally_unique_identifier) for idempotency keys to avoid collisions.

        Idempotency keys expire after 24 hours. The API will generate a new response if you submit a request with an expired key.

        Args:
            organization_id: The unique ID of the Organization.
            event: The audit log event to create.
            idempotency_key: Optional idempotency key for safe retries.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            AuditLogEventCreateResponse

        Raises:
            BadRequestError: If the request is malformed (400).
            NotFoundError: If the resource is not found (404).
            UnprocessableEntityError: If the request data is unprocessable (422).
            RateLimitExceededError: If rate limited (429).
            AuthenticationError: If the API key is invalid (401).
            ServerError: If the server returns a 5xx error.
        """
        body: Dict[str, Any] = {
            "organization_id": organization_id,
            "event": event.to_dict(),
        }
        return await self._client.request(
            method="post",
            path=("audit_logs", "events"),
            body=body,
            model=AuditLogEventCreateResponse,
            idempotency_key=idempotency_key,
            request_options=request_options,
        )

    async def create_export(
        self,
        *,
        organization_id: str,
        range_start: str,
        range_end: str,
        actions: Optional[List[str]] = None,
        actors: Optional[List[str]] = None,
        actor_names: Optional[List[str]] = None,
        actor_ids: Optional[List[str]] = None,
        targets: Optional[List[str]] = None,
        request_options: Optional[RequestOptions] = None,
    ) -> AuditLogExport:
        """Create Export

        Create an Audit Log Export. Exports are scoped to a single organization within a specified date range.

        Args:
            organization_id: The unique ID of the Organization.
            range_start: ISO-8601 value for start of the export range.
            range_end: ISO-8601 value for end of the export range.
            actions: List of actions to filter against.
            actors: (deprecated) Deprecated. Use `actor_names` instead.
            actor_names: List of actor names to filter against.
            actor_ids: List of actor IDs to filter against.
            targets: List of target types to filter against.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            AuditLogExport

        Raises:
            BadRequestError: If the request is malformed (400).
            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 {
                "organization_id": organization_id,
                "range_start": range_start,
                "range_end": range_end,
                "actions": actions,
                "actors": actors,
                "actor_names": actor_names,
                "actor_ids": actor_ids,
                "targets": targets,
            }.items()
            if v is not None
        }
        return await self._client.request(
            method="post",
            path=("audit_logs", "exports"),
            body=body,
            model=AuditLogExport,
            request_options=request_options,
        )

    async def get_export(
        self,
        audit_log_export_id: str,
        *,
        request_options: Optional[RequestOptions] = None,
    ) -> AuditLogExport:
        """Get Export

        Get an Audit Log Export. The URL will expire after 10 minutes. If the export is needed again at a later time, refetching the export will regenerate the URL.

        Args:
            audit_log_export_id: The unique ID of the Audit Log Export.
            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.

        Returns:
            AuditLogExport

        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.
        """
        return await self._client.request(
            method="get",
            path=("audit_logs", "exports", str(audit_log_export_id)),
            model=AuditLogExport,
            request_options=request_options,
        )
