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

import json

import pytest
from workos import WorkOSClient, AsyncWorkOSClient
from tests.generated_helpers import load_fixture

from workos.audit_logs.models import (
    AuditLogAction,
    AuditLogEvent,
    AuditLogEventCreateResponse,
    AuditLogExport,
    AuditLogSchema,
)
from workos.common.models import PaginationOrder
from workos.organizations.models import AuditLogsRetention
from workos._pagination import AsyncPage, SyncPage
from workos._errors import (
    AuthenticationError,
    BadRequestError,
    NotFoundError,
    RateLimitExceededError,
    ServerError,
    UnprocessableEntityError,
)


class TestAuditLogs:
    def test_get_organization_audit_logs_retention(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("audit_logs_retention.json"),
        )
        result = workos.audit_logs.get_organization_audit_logs_retention("test_id")
        assert isinstance(result, AuditLogsRetention)
        assert result.retention_period_in_days == 30
        request = httpx_mock.get_request()
        assert request.method == "GET"
        assert request.url.path.endswith("/organizations/test_id/audit_logs_retention")

    def test_update_organization_audit_logs_retention(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("audit_logs_retention.json"),
        )
        result = workos.audit_logs.update_organization_audit_logs_retention(
            "test_id", retention_period_in_days=1
        )
        assert isinstance(result, AuditLogsRetention)
        assert result.retention_period_in_days == 30
        request = httpx_mock.get_request()
        assert request.method == "PUT"
        assert request.url.path.endswith("/organizations/test_id/audit_logs_retention")
        body = json.loads(request.content)
        assert body["retention_period_in_days"] == 1

    def test_list_actions(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("list_audit_log_action.json"),
        )
        page = workos.audit_logs.list_actions()
        assert isinstance(page, SyncPage)
        assert len(page.data) == 1
        assert isinstance(page.data[0], AuditLogAction)

    def test_list_actions_empty_page(self, workos, httpx_mock):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        page = workos.audit_logs.list_actions()
        assert isinstance(page, SyncPage)
        assert page.data == []

    def test_list_actions_encodes_query_params(self, workos, httpx_mock):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        workos.audit_logs.list_actions(
            limit=10,
            before="cursor before",
            after="cursor/after",
            order=PaginationOrder("value_order"),
        )
        request = httpx_mock.get_request()
        assert request.url.params["limit"] == "10"
        assert request.url.params["before"] == "cursor before"
        assert request.url.params["after"] == "cursor/after"
        assert request.url.params["order"] == "value_order"

    def test_list_action_schemas(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("list_audit_log_schema.json"),
        )
        page = workos.audit_logs.list_action_schemas("test_actionName")
        assert isinstance(page, SyncPage)
        assert len(page.data) == 1
        assert isinstance(page.data[0], AuditLogSchema)

    def test_list_action_schemas_empty_page(self, workos, httpx_mock):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        page = workos.audit_logs.list_action_schemas("test_actionName")
        assert isinstance(page, SyncPage)
        assert page.data == []

    def test_list_action_schemas_encodes_query_params(self, workos, httpx_mock):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        workos.audit_logs.list_action_schemas(
            "test_actionName",
            limit=10,
            before="cursor before",
            after="cursor/after",
            order=PaginationOrder("value_order"),
        )
        request = httpx_mock.get_request()
        assert request.url.params["limit"] == "10"
        assert request.url.params["before"] == "cursor before"
        assert request.url.params["after"] == "cursor/after"
        assert request.url.params["order"] == "value_order"

    def test_create_schema(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("audit_log_schema.json"),
        )
        result = workos.audit_logs.create_schema("test_actionName", targets=[])
        assert isinstance(result, AuditLogSchema)
        assert result.object == "audit_log_schema"
        assert result.version == 1
        request = httpx_mock.get_request()
        assert request.method == "POST"
        assert request.url.path.endswith("/audit_logs/actions/test_actionName/schemas")
        body = json.loads(request.content)
        assert "targets" in body

    def test_create_event(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("audit_log_event_create_response.json"),
        )
        result = workos.audit_logs.create_event(
            organization_id="test_organization_id",
            event=AuditLogEvent.from_dict(load_fixture("audit_log_event.json")),
        )
        assert isinstance(result, AuditLogEventCreateResponse)
        assert result.success is True
        request = httpx_mock.get_request()
        assert request.method == "POST"
        assert request.url.path.endswith("/audit_logs/events")
        body = json.loads(request.content)
        assert body["organization_id"] == "test_organization_id"
        assert "event" in body

    def test_create_export(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("audit_log_export.json"),
        )
        result = workos.audit_logs.create_export(
            organization_id="test_organization_id",
            range_start="test_range_start",
            range_end="test_range_end",
        )
        assert isinstance(result, AuditLogExport)
        assert result.object == "audit_log_export"
        assert result.id == "audit_log_export_01GBZK5MP7TD1YCFQHFR22180V"
        request = httpx_mock.get_request()
        assert request.method == "POST"
        assert request.url.path.endswith("/audit_logs/exports")
        body = json.loads(request.content)
        assert body["organization_id"] == "test_organization_id"
        assert body["range_start"] == "test_range_start"
        assert body["range_end"] == "test_range_end"

    def test_get_export(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("audit_log_export.json"),
        )
        result = workos.audit_logs.get_export("test_auditLogExportId")
        assert isinstance(result, AuditLogExport)
        assert result.object == "audit_log_export"
        assert result.id == "audit_log_export_01GBZK5MP7TD1YCFQHFR22180V"
        request = httpx_mock.get_request()
        assert request.method == "GET"
        assert request.url.path.endswith("/audit_logs/exports/test_auditLogExportId")

    def test_get_organization_audit_logs_retention_with_request_options(
        self, workos, httpx_mock
    ):
        httpx_mock.add_response(json=load_fixture("audit_logs_retention.json"))
        workos.audit_logs.get_organization_audit_logs_retention(
            "test_id", request_options={"extra_headers": {"X-Custom": "value"}}
        )
        request = httpx_mock.get_request()
        assert request.headers["X-Custom"] == "value"

    def test_get_organization_audit_logs_retention_unauthorized(
        self, workos, httpx_mock
    ):
        httpx_mock.add_response(
            status_code=401,
            json={"message": "Unauthorized"},
        )
        with pytest.raises(AuthenticationError):
            workos.audit_logs.get_organization_audit_logs_retention("test_id")

    def test_get_organization_audit_logs_retention_not_found(self, httpx_mock):
        workos = WorkOSClient(
            api_key="sk_test_123", client_id="client_test", max_retries=0
        )
        try:
            httpx_mock.add_response(status_code=404, json={"message": "Not found"})
            with pytest.raises(NotFoundError):
                workos.audit_logs.get_organization_audit_logs_retention("test_id")
        finally:
            workos.close()

    def test_get_organization_audit_logs_retention_rate_limited(self, httpx_mock):
        workos = WorkOSClient(
            api_key="sk_test_123", client_id="client_test", max_retries=0
        )
        try:
            httpx_mock.add_response(
                status_code=429,
                headers={"Retry-After": "0"},
                json={"message": "Slow down"},
            )
            with pytest.raises(RateLimitExceededError):
                workos.audit_logs.get_organization_audit_logs_retention("test_id")
        finally:
            workos.close()

    def test_get_organization_audit_logs_retention_server_error(self, httpx_mock):
        workos = WorkOSClient(
            api_key="sk_test_123", client_id="client_test", max_retries=0
        )
        try:
            httpx_mock.add_response(status_code=500, json={"message": "Server error"})
            with pytest.raises(ServerError):
                workos.audit_logs.get_organization_audit_logs_retention("test_id")
        finally:
            workos.close()

    def test_get_organization_audit_logs_retention_bad_request(self, httpx_mock):
        workos = WorkOSClient(
            api_key="sk_test_123", client_id="client_test", max_retries=0
        )
        try:
            httpx_mock.add_response(status_code=400, json={"message": "Bad request"})
            with pytest.raises(BadRequestError):
                workos.audit_logs.get_organization_audit_logs_retention("test_id")
        finally:
            workos.close()

    def test_get_organization_audit_logs_retention_unprocessable(self, httpx_mock):
        workos = WorkOSClient(
            api_key="sk_test_123", client_id="client_test", max_retries=0
        )
        try:
            httpx_mock.add_response(status_code=422, json={"message": "Unprocessable"})
            with pytest.raises(UnprocessableEntityError):
                workos.audit_logs.get_organization_audit_logs_retention("test_id")
        finally:
            workos.close()


class TestAsyncAuditLogs:
    @pytest.mark.asyncio
    async def test_get_organization_audit_logs_retention(
        self, async_workos, httpx_mock
    ):
        httpx_mock.add_response(json=load_fixture("audit_logs_retention.json"))
        result = await async_workos.audit_logs.get_organization_audit_logs_retention(
            "test_id"
        )
        assert isinstance(result, AuditLogsRetention)
        assert result.retention_period_in_days == 30
        request = httpx_mock.get_request()
        assert request.method == "GET"
        assert request.url.path.endswith("/organizations/test_id/audit_logs_retention")

    @pytest.mark.asyncio
    async def test_update_organization_audit_logs_retention(
        self, async_workos, httpx_mock
    ):
        httpx_mock.add_response(json=load_fixture("audit_logs_retention.json"))
        result = await async_workos.audit_logs.update_organization_audit_logs_retention(
            "test_id", retention_period_in_days=1
        )
        assert isinstance(result, AuditLogsRetention)
        assert result.retention_period_in_days == 30
        request = httpx_mock.get_request()
        assert request.method == "PUT"
        assert request.url.path.endswith("/organizations/test_id/audit_logs_retention")

    @pytest.mark.asyncio
    async def test_list_actions(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("list_audit_log_action.json"))
        page = await async_workos.audit_logs.list_actions()
        assert isinstance(page, AsyncPage)
        assert len(page.data) == 1
        assert isinstance(page.data[0], AuditLogAction)

    @pytest.mark.asyncio
    async def test_list_actions_empty_page(self, async_workos, httpx_mock):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        page = await async_workos.audit_logs.list_actions()
        assert isinstance(page, AsyncPage)
        assert page.data == []

    @pytest.mark.asyncio
    async def test_list_actions_encodes_query_params(self, async_workos, httpx_mock):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        await async_workos.audit_logs.list_actions(
            limit=10,
            before="cursor before",
            after="cursor/after",
            order=PaginationOrder("value_order"),
        )
        request = httpx_mock.get_request()
        assert request.url.params["limit"] == "10"
        assert request.url.params["before"] == "cursor before"
        assert request.url.params["after"] == "cursor/after"
        assert request.url.params["order"] == "value_order"

    @pytest.mark.asyncio
    async def test_list_action_schemas(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("list_audit_log_schema.json"))
        page = await async_workos.audit_logs.list_action_schemas("test_actionName")
        assert isinstance(page, AsyncPage)
        assert len(page.data) == 1
        assert isinstance(page.data[0], AuditLogSchema)

    @pytest.mark.asyncio
    async def test_list_action_schemas_empty_page(self, async_workos, httpx_mock):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        page = await async_workos.audit_logs.list_action_schemas("test_actionName")
        assert isinstance(page, AsyncPage)
        assert page.data == []

    @pytest.mark.asyncio
    async def test_list_action_schemas_encodes_query_params(
        self, async_workos, httpx_mock
    ):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        await async_workos.audit_logs.list_action_schemas(
            "test_actionName",
            limit=10,
            before="cursor before",
            after="cursor/after",
            order=PaginationOrder("value_order"),
        )
        request = httpx_mock.get_request()
        assert request.url.params["limit"] == "10"
        assert request.url.params["before"] == "cursor before"
        assert request.url.params["after"] == "cursor/after"
        assert request.url.params["order"] == "value_order"

    @pytest.mark.asyncio
    async def test_create_schema(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("audit_log_schema.json"))
        result = await async_workos.audit_logs.create_schema(
            "test_actionName", targets=[]
        )
        assert isinstance(result, AuditLogSchema)
        assert result.object == "audit_log_schema"
        assert result.version == 1
        request = httpx_mock.get_request()
        assert request.method == "POST"
        assert request.url.path.endswith("/audit_logs/actions/test_actionName/schemas")

    @pytest.mark.asyncio
    async def test_create_event(self, async_workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("audit_log_event_create_response.json")
        )
        result = await async_workos.audit_logs.create_event(
            organization_id="test_organization_id",
            event=AuditLogEvent.from_dict(load_fixture("audit_log_event.json")),
        )
        assert isinstance(result, AuditLogEventCreateResponse)
        assert result.success is True
        request = httpx_mock.get_request()
        assert request.method == "POST"
        assert request.url.path.endswith("/audit_logs/events")

    @pytest.mark.asyncio
    async def test_create_export(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("audit_log_export.json"))
        result = await async_workos.audit_logs.create_export(
            organization_id="test_organization_id",
            range_start="test_range_start",
            range_end="test_range_end",
        )
        assert isinstance(result, AuditLogExport)
        assert result.object == "audit_log_export"
        assert result.id == "audit_log_export_01GBZK5MP7TD1YCFQHFR22180V"
        request = httpx_mock.get_request()
        assert request.method == "POST"
        assert request.url.path.endswith("/audit_logs/exports")

    @pytest.mark.asyncio
    async def test_get_export(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("audit_log_export.json"))
        result = await async_workos.audit_logs.get_export("test_auditLogExportId")
        assert isinstance(result, AuditLogExport)
        assert result.object == "audit_log_export"
        assert result.id == "audit_log_export_01GBZK5MP7TD1YCFQHFR22180V"
        request = httpx_mock.get_request()
        assert request.method == "GET"
        assert request.url.path.endswith("/audit_logs/exports/test_auditLogExportId")

    @pytest.mark.asyncio
    async def test_get_organization_audit_logs_retention_with_request_options(
        self, async_workos, httpx_mock
    ):
        httpx_mock.add_response(json=load_fixture("audit_logs_retention.json"))
        await async_workos.audit_logs.get_organization_audit_logs_retention(
            "test_id", request_options={"extra_headers": {"X-Custom": "value"}}
        )
        request = httpx_mock.get_request()
        assert request.headers["X-Custom"] == "value"

    @pytest.mark.asyncio
    async def test_get_organization_audit_logs_retention_unauthorized(
        self, async_workos, httpx_mock
    ):
        httpx_mock.add_response(status_code=401, json={"message": "Unauthorized"})
        with pytest.raises(AuthenticationError):
            await async_workos.audit_logs.get_organization_audit_logs_retention(
                "test_id"
            )

    @pytest.mark.asyncio
    async def test_get_organization_audit_logs_retention_not_found(self, httpx_mock):
        workos = AsyncWorkOSClient(
            api_key="sk_test_123", client_id="client_test", max_retries=0
        )
        try:
            httpx_mock.add_response(status_code=404, json={"message": "Not found"})
            with pytest.raises(NotFoundError):
                await workos.audit_logs.get_organization_audit_logs_retention("test_id")
        finally:
            await workos.close()

    @pytest.mark.asyncio
    async def test_get_organization_audit_logs_retention_rate_limited(self, httpx_mock):
        workos = AsyncWorkOSClient(
            api_key="sk_test_123", client_id="client_test", max_retries=0
        )
        try:
            httpx_mock.add_response(
                status_code=429,
                headers={"Retry-After": "0"},
                json={"message": "Slow down"},
            )
            with pytest.raises(RateLimitExceededError):
                await workos.audit_logs.get_organization_audit_logs_retention("test_id")
        finally:
            await workos.close()

    @pytest.mark.asyncio
    async def test_get_organization_audit_logs_retention_server_error(self, httpx_mock):
        workos = AsyncWorkOSClient(
            api_key="sk_test_123", client_id="client_test", max_retries=0
        )
        try:
            httpx_mock.add_response(status_code=500, json={"message": "Server error"})
            with pytest.raises(ServerError):
                await workos.audit_logs.get_organization_audit_logs_retention("test_id")
        finally:
            await workos.close()

    @pytest.mark.asyncio
    async def test_get_organization_audit_logs_retention_bad_request(self, httpx_mock):
        workos = AsyncWorkOSClient(
            api_key="sk_test_123", client_id="client_test", max_retries=0
        )
        try:
            httpx_mock.add_response(status_code=400, json={"message": "Bad request"})
            with pytest.raises(BadRequestError):
                await workos.audit_logs.get_organization_audit_logs_retention("test_id")
        finally:
            await workos.close()

    @pytest.mark.asyncio
    async def test_get_organization_audit_logs_retention_unprocessable(
        self, httpx_mock
    ):
        workos = AsyncWorkOSClient(
            api_key="sk_test_123", client_id="client_test", max_retries=0
        )
        try:
            httpx_mock.add_response(status_code=422, json={"message": "Unprocessable"})
            with pytest.raises(UnprocessableEntityError):
                await workos.audit_logs.get_organization_audit_logs_retention("test_id")
        finally:
            await workos.close()
