# 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.common.models import PaginationOrder
from workos.organizations.models import (
    AuditLogConfiguration,
    Organization,
    OrganizationAuthorizedConnectApplicationListData,
)
from workos._pagination import AsyncPage, SyncPage
from workos._errors import (
    AuthenticationError,
    BadRequestError,
    NotFoundError,
    RateLimitExceededError,
    ServerError,
    UnprocessableEntityError,
)


class TestOrganizations:
    def test_list_organizations(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("list_organization.json"),
        )
        page = workos.organizations.list_organizations()
        assert isinstance(page, SyncPage)
        assert len(page.data) == 1
        assert isinstance(page.data[0], Organization)

    def test_list_organizations_empty_page(self, workos, httpx_mock):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        page = workos.organizations.list_organizations()
        assert isinstance(page, SyncPage)
        assert page.data == []

    def test_list_organizations_encodes_query_params(self, workos, httpx_mock):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        workos.organizations.list_organizations(
            limit=10,
            before="cursor before",
            after="cursor/after",
            order=PaginationOrder("value_order"),
            domains=["val1", "val2"],
            search="value search/test",
        )
        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"
        assert request.url.params["domains"] == "val1,val2"
        assert request.url.params["search"] == "value search/test"

    def test_create_organization(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("organization.json"),
        )
        result = workos.organizations.create_organization(name="test_name")
        assert isinstance(result, Organization)
        assert result.object == "organization"
        assert result.id == "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
        request = httpx_mock.get_request()
        assert request.method == "POST"
        assert request.url.path.endswith("/organizations")
        body = json.loads(request.content)
        assert body["name"] == "test_name"

    def test_get_organization_by_external_id(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("organization.json"),
        )
        result = workos.organizations.get_organization_by_external_id(
            "test_external_id"
        )
        assert isinstance(result, Organization)
        assert result.object == "organization"
        assert result.id == "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
        request = httpx_mock.get_request()
        assert request.method == "GET"
        assert request.url.path.endswith("/organizations/external_id/test_external_id")

    def test_get_organization(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("organization.json"),
        )
        result = workos.organizations.get_organization("test_id")
        assert isinstance(result, Organization)
        assert result.object == "organization"
        assert result.id == "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
        request = httpx_mock.get_request()
        assert request.method == "GET"
        assert request.url.path.endswith("/organizations/test_id")

    def test_update_organization(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("organization.json"),
        )
        result = workos.organizations.update_organization("test_id")
        assert isinstance(result, Organization)
        assert result.object == "organization"
        assert result.id == "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
        request = httpx_mock.get_request()
        assert request.method == "PUT"
        assert request.url.path.endswith("/organizations/test_id")

    def test_delete_organization(self, workos, httpx_mock):
        httpx_mock.add_response(status_code=200, content=b"\n")
        result = workos.organizations.delete_organization("test_id")
        assert result is None
        request = httpx_mock.get_request()
        assert request.method == "DELETE"
        assert request.url.path.endswith("/organizations/test_id")

    def test_get_audit_log_configuration(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("audit_log_configuration.json"),
        )
        result = workos.organizations.get_audit_log_configuration("test_id")
        assert isinstance(result, AuditLogConfiguration)
        assert result.organization_id == "org_01EHZNVPK3SFK441A1RGBFSHRT"
        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_log_configuration"
        )

    def test_list_authorized_applications(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture(
                "list_organization_authorized_connect_application_list_data.json"
            ),
        )
        page = workos.organizations.list_authorized_applications("test_organization_id")
        assert isinstance(page, SyncPage)
        assert len(page.data) == 1
        assert isinstance(
            page.data[0], OrganizationAuthorizedConnectApplicationListData
        )

    def test_list_authorized_applications_empty_page(self, workos, httpx_mock):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        page = workos.organizations.list_authorized_applications("test_organization_id")
        assert isinstance(page, SyncPage)
        assert page.data == []

    def test_list_authorized_applications_encodes_query_params(
        self, workos, httpx_mock
    ):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        workos.organizations.list_authorized_applications(
            "test_organization_id",
            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_organizations_with_request_options(self, workos, httpx_mock):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        workos.organizations.list_organizations(
            request_options={"extra_headers": {"X-Custom": "value"}}
        )
        request = httpx_mock.get_request()
        assert request.headers["X-Custom"] == "value"

    def test_list_organizations_unauthorized(self, workos, httpx_mock):
        httpx_mock.add_response(
            status_code=401,
            json={"message": "Unauthorized"},
        )
        with pytest.raises(AuthenticationError):
            workos.organizations.list_organizations()

    def test_list_organizations_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.organizations.list_organizations()
        finally:
            workos.close()

    def test_list_organizations_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.organizations.list_organizations()
        finally:
            workos.close()

    def test_list_organizations_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.organizations.list_organizations()
        finally:
            workos.close()

    def test_list_organizations_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.organizations.list_organizations()
        finally:
            workos.close()

    def test_list_organizations_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.organizations.list_organizations()
        finally:
            workos.close()


class TestAsyncOrganizations:
    @pytest.mark.asyncio
    async def test_list_organizations(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("list_organization.json"))
        page = await async_workos.organizations.list_organizations()
        assert isinstance(page, AsyncPage)
        assert len(page.data) == 1
        assert isinstance(page.data[0], Organization)

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

    @pytest.mark.asyncio
    async def test_list_organizations_encodes_query_params(
        self, async_workos, httpx_mock
    ):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        await async_workos.organizations.list_organizations(
            limit=10,
            before="cursor before",
            after="cursor/after",
            order=PaginationOrder("value_order"),
            domains=["val1", "val2"],
            search="value search/test",
        )
        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"
        assert request.url.params["domains"] == "val1,val2"
        assert request.url.params["search"] == "value search/test"

    @pytest.mark.asyncio
    async def test_create_organization(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("organization.json"))
        result = await async_workos.organizations.create_organization(name="test_name")
        assert isinstance(result, Organization)
        assert result.object == "organization"
        assert result.id == "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
        request = httpx_mock.get_request()
        assert request.method == "POST"
        assert request.url.path.endswith("/organizations")

    @pytest.mark.asyncio
    async def test_get_organization_by_external_id(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("organization.json"))
        result = await async_workos.organizations.get_organization_by_external_id(
            "test_external_id"
        )
        assert isinstance(result, Organization)
        assert result.object == "organization"
        assert result.id == "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
        request = httpx_mock.get_request()
        assert request.method == "GET"
        assert request.url.path.endswith("/organizations/external_id/test_external_id")

    @pytest.mark.asyncio
    async def test_get_organization(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("organization.json"))
        result = await async_workos.organizations.get_organization("test_id")
        assert isinstance(result, Organization)
        assert result.object == "organization"
        assert result.id == "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
        request = httpx_mock.get_request()
        assert request.method == "GET"
        assert request.url.path.endswith("/organizations/test_id")

    @pytest.mark.asyncio
    async def test_update_organization(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("organization.json"))
        result = await async_workos.organizations.update_organization("test_id")
        assert isinstance(result, Organization)
        assert result.object == "organization"
        assert result.id == "org_01EHWNCE74X7JSDV0X3SZ3KJNY"
        request = httpx_mock.get_request()
        assert request.method == "PUT"
        assert request.url.path.endswith("/organizations/test_id")

    @pytest.mark.asyncio
    async def test_delete_organization(self, async_workos, httpx_mock):
        httpx_mock.add_response(status_code=200, content=b"\n")
        result = await async_workos.organizations.delete_organization("test_id")
        assert result is None
        request = httpx_mock.get_request()
        assert request.method == "DELETE"
        assert request.url.path.endswith("/organizations/test_id")

    @pytest.mark.asyncio
    async def test_get_audit_log_configuration(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("audit_log_configuration.json"))
        result = await async_workos.organizations.get_audit_log_configuration("test_id")
        assert isinstance(result, AuditLogConfiguration)
        assert result.organization_id == "org_01EHZNVPK3SFK441A1RGBFSHRT"
        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_log_configuration"
        )

    @pytest.mark.asyncio
    async def test_list_authorized_applications(self, async_workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture(
                "list_organization_authorized_connect_application_list_data.json"
            )
        )
        page = await async_workos.organizations.list_authorized_applications(
            "test_organization_id"
        )
        assert isinstance(page, AsyncPage)
        assert len(page.data) == 1
        assert isinstance(
            page.data[0], OrganizationAuthorizedConnectApplicationListData
        )

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

    @pytest.mark.asyncio
    async def test_list_authorized_applications_encodes_query_params(
        self, async_workos, httpx_mock
    ):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        await async_workos.organizations.list_authorized_applications(
            "test_organization_id",
            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_organizations_with_request_options(
        self, async_workos, httpx_mock
    ):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        await async_workos.organizations.list_organizations(
            request_options={"extra_headers": {"X-Custom": "value"}}
        )
        request = httpx_mock.get_request()
        assert request.headers["X-Custom"] == "value"

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

    @pytest.mark.asyncio
    async def test_list_organizations_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.organizations.list_organizations()
        finally:
            await workos.close()

    @pytest.mark.asyncio
    async def test_list_organizations_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.organizations.list_organizations()
        finally:
            await workos.close()

    @pytest.mark.asyncio
    async def test_list_organizations_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.organizations.list_organizations()
        finally:
            await workos.close()

    @pytest.mark.asyncio
    async def test_list_organizations_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.organizations.list_organizations()
        finally:
            await workos.close()

    @pytest.mark.asyncio
    async def test_list_organizations_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.organizations.list_organizations()
        finally:
            await workos.close()
