# 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 Group, PaginationOrder
from workos.organization_membership.models import (
    OrganizationMembership,
    UserOrganizationMembership,
)
from workos._pagination import AsyncPage, SyncPage
from workos._errors import (
    AuthenticationError,
    BadRequestError,
    NotFoundError,
    RateLimitExceededError,
    ServerError,
    UnprocessableEntityError,
)
from workos.organization_membership._resource import RoleSingle


class TestOrganizationMembership:
    def test_list_organization_memberships(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("list_user_organization_membership.json"),
        )
        page = workos.organization_membership.list_organization_memberships()
        assert isinstance(page, SyncPage)
        assert len(page.data) == 1
        assert isinstance(page.data[0], UserOrganizationMembership)

    def test_list_organization_memberships_empty_page(self, workos, httpx_mock):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        page = workos.organization_membership.list_organization_memberships()
        assert isinstance(page, SyncPage)
        assert page.data == []

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

    def test_create_organization_membership(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("organization_membership.json"),
        )
        result = workos.organization_membership.create_organization_membership(
            user_id="test_user_id",
            organization_id="test_organization_id",
            role=RoleSingle(role_slug="test_value"),
        )
        assert isinstance(result, OrganizationMembership)
        assert result.object == "organization_membership"
        assert result.id == "om_01HXYZ123456789ABCDEFGHIJ"
        request = httpx_mock.get_request()
        assert request.method == "POST"
        assert request.url.path.endswith("/user_management/organization_memberships")
        body = json.loads(request.content)
        assert body["user_id"] == "test_user_id"
        assert body["organization_id"] == "test_organization_id"

    def test_get_organization_membership(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("user_organization_membership.json"),
        )
        result = workos.organization_membership.get_organization_membership("test_id")
        assert isinstance(result, UserOrganizationMembership)
        assert result.object == "organization_membership"
        assert result.id == "om_01HXYZ123456789ABCDEFGHIJ"
        request = httpx_mock.get_request()
        assert request.method == "GET"
        assert request.url.path.endswith(
            "/user_management/organization_memberships/test_id"
        )

    def test_update_organization_membership(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("user_organization_membership.json"),
        )
        result = workos.organization_membership.update_organization_membership(
            "test_id", role=RoleSingle(role_slug="test_value")
        )
        assert isinstance(result, UserOrganizationMembership)
        assert result.object == "organization_membership"
        assert result.id == "om_01HXYZ123456789ABCDEFGHIJ"
        request = httpx_mock.get_request()
        assert request.method == "PUT"
        assert request.url.path.endswith(
            "/user_management/organization_memberships/test_id"
        )

    def test_delete_organization_membership(self, workos, httpx_mock):
        httpx_mock.add_response(status_code=204)
        result = workos.organization_membership.delete_organization_membership(
            "test_id"
        )
        assert result is None
        request = httpx_mock.get_request()
        assert request.method == "DELETE"
        assert request.url.path.endswith(
            "/user_management/organization_memberships/test_id"
        )

    def test_deactivate_organization_membership(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("organization_membership.json"),
        )
        result = workos.organization_membership.deactivate_organization_membership(
            "test_id"
        )
        assert isinstance(result, OrganizationMembership)
        assert result.object == "organization_membership"
        assert result.id == "om_01HXYZ123456789ABCDEFGHIJ"
        request = httpx_mock.get_request()
        assert request.method == "PUT"
        assert request.url.path.endswith(
            "/user_management/organization_memberships/test_id/deactivate"
        )

    def test_reactivate_organization_membership(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("user_organization_membership.json"),
        )
        result = workos.organization_membership.reactivate_organization_membership(
            "test_id"
        )
        assert isinstance(result, UserOrganizationMembership)
        assert result.object == "organization_membership"
        assert result.id == "om_01HXYZ123456789ABCDEFGHIJ"
        request = httpx_mock.get_request()
        assert request.method == "PUT"
        assert request.url.path.endswith(
            "/user_management/organization_memberships/test_id/reactivate"
        )

    def test_list_organization_membership_groups(self, workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("list_group.json"),
        )
        page = workos.organization_membership.list_organization_membership_groups(
            "test_omId"
        )
        assert isinstance(page, SyncPage)
        assert len(page.data) == 1
        assert isinstance(page.data[0], Group)

    def test_list_organization_membership_groups_empty_page(self, workos, httpx_mock):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        page = workos.organization_membership.list_organization_membership_groups(
            "test_omId"
        )
        assert isinstance(page, SyncPage)
        assert page.data == []

    def test_list_organization_membership_groups_encodes_query_params(
        self, workos, httpx_mock
    ):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        workos.organization_membership.list_organization_membership_groups(
            "test_omId",
            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_organization_memberships_with_request_options(
        self, workos, httpx_mock
    ):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        workos.organization_membership.list_organization_memberships(
            request_options={"extra_headers": {"X-Custom": "value"}}
        )
        request = httpx_mock.get_request()
        assert request.headers["X-Custom"] == "value"

    def test_list_organization_memberships_unauthorized(self, workos, httpx_mock):
        httpx_mock.add_response(
            status_code=401,
            json={"message": "Unauthorized"},
        )
        with pytest.raises(AuthenticationError):
            workos.organization_membership.list_organization_memberships()

    def test_list_organization_memberships_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.organization_membership.list_organization_memberships()
        finally:
            workos.close()

    def test_list_organization_memberships_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.organization_membership.list_organization_memberships()
        finally:
            workos.close()

    def test_list_organization_memberships_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.organization_membership.list_organization_memberships()
        finally:
            workos.close()

    def test_list_organization_memberships_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.organization_membership.list_organization_memberships()
        finally:
            workos.close()

    def test_list_organization_memberships_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.organization_membership.list_organization_memberships()
        finally:
            workos.close()


class TestAsyncOrganizationMembership:
    @pytest.mark.asyncio
    async def test_list_organization_memberships(self, async_workos, httpx_mock):
        httpx_mock.add_response(
            json=load_fixture("list_user_organization_membership.json")
        )
        page = (
            await async_workos.organization_membership.list_organization_memberships()
        )
        assert isinstance(page, AsyncPage)
        assert len(page.data) == 1
        assert isinstance(page.data[0], UserOrganizationMembership)

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

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

    @pytest.mark.asyncio
    async def test_create_organization_membership(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("organization_membership.json"))
        result = (
            await async_workos.organization_membership.create_organization_membership(
                user_id="test_user_id",
                organization_id="test_organization_id",
                role=RoleSingle(role_slug="test_value"),
            )
        )
        assert isinstance(result, OrganizationMembership)
        assert result.object == "organization_membership"
        assert result.id == "om_01HXYZ123456789ABCDEFGHIJ"
        request = httpx_mock.get_request()
        assert request.method == "POST"
        assert request.url.path.endswith("/user_management/organization_memberships")

    @pytest.mark.asyncio
    async def test_get_organization_membership(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("user_organization_membership.json"))
        result = await async_workos.organization_membership.get_organization_membership(
            "test_id"
        )
        assert isinstance(result, UserOrganizationMembership)
        assert result.object == "organization_membership"
        assert result.id == "om_01HXYZ123456789ABCDEFGHIJ"
        request = httpx_mock.get_request()
        assert request.method == "GET"
        assert request.url.path.endswith(
            "/user_management/organization_memberships/test_id"
        )

    @pytest.mark.asyncio
    async def test_update_organization_membership(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("user_organization_membership.json"))
        result = (
            await async_workos.organization_membership.update_organization_membership(
                "test_id", role=RoleSingle(role_slug="test_value")
            )
        )
        assert isinstance(result, UserOrganizationMembership)
        assert result.object == "organization_membership"
        assert result.id == "om_01HXYZ123456789ABCDEFGHIJ"
        request = httpx_mock.get_request()
        assert request.method == "PUT"
        assert request.url.path.endswith(
            "/user_management/organization_memberships/test_id"
        )

    @pytest.mark.asyncio
    async def test_delete_organization_membership(self, async_workos, httpx_mock):
        httpx_mock.add_response(status_code=204)
        result = (
            await async_workos.organization_membership.delete_organization_membership(
                "test_id"
            )
        )
        assert result is None
        request = httpx_mock.get_request()
        assert request.method == "DELETE"
        assert request.url.path.endswith(
            "/user_management/organization_memberships/test_id"
        )

    @pytest.mark.asyncio
    async def test_deactivate_organization_membership(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("organization_membership.json"))
        result = await async_workos.organization_membership.deactivate_organization_membership(
            "test_id"
        )
        assert isinstance(result, OrganizationMembership)
        assert result.object == "organization_membership"
        assert result.id == "om_01HXYZ123456789ABCDEFGHIJ"
        request = httpx_mock.get_request()
        assert request.method == "PUT"
        assert request.url.path.endswith(
            "/user_management/organization_memberships/test_id/deactivate"
        )

    @pytest.mark.asyncio
    async def test_reactivate_organization_membership(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("user_organization_membership.json"))
        result = await async_workos.organization_membership.reactivate_organization_membership(
            "test_id"
        )
        assert isinstance(result, UserOrganizationMembership)
        assert result.object == "organization_membership"
        assert result.id == "om_01HXYZ123456789ABCDEFGHIJ"
        request = httpx_mock.get_request()
        assert request.method == "PUT"
        assert request.url.path.endswith(
            "/user_management/organization_memberships/test_id/reactivate"
        )

    @pytest.mark.asyncio
    async def test_list_organization_membership_groups(self, async_workos, httpx_mock):
        httpx_mock.add_response(json=load_fixture("list_group.json"))
        page = await async_workos.organization_membership.list_organization_membership_groups(
            "test_omId"
        )
        assert isinstance(page, AsyncPage)
        assert len(page.data) == 1
        assert isinstance(page.data[0], Group)

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

    @pytest.mark.asyncio
    async def test_list_organization_membership_groups_encodes_query_params(
        self, async_workos, httpx_mock
    ):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        await async_workos.organization_membership.list_organization_membership_groups(
            "test_omId",
            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_organization_memberships_with_request_options(
        self, async_workos, httpx_mock
    ):
        httpx_mock.add_response(json={"data": [], "list_metadata": {}})
        await async_workos.organization_membership.list_organization_memberships(
            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_organization_memberships_unauthorized(
        self, async_workos, httpx_mock
    ):
        httpx_mock.add_response(status_code=401, json={"message": "Unauthorized"})
        with pytest.raises(AuthenticationError):
            await async_workos.organization_membership.list_organization_memberships()

    @pytest.mark.asyncio
    async def test_list_organization_memberships_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.organization_membership.list_organization_memberships()
        finally:
            await workos.close()

    @pytest.mark.asyncio
    async def test_list_organization_memberships_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.organization_membership.list_organization_memberships()
        finally:
            await workos.close()

    @pytest.mark.asyncio
    async def test_list_organization_memberships_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.organization_membership.list_organization_memberships()
        finally:
            await workos.close()

    @pytest.mark.asyncio
    async def test_list_organization_memberships_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.organization_membership.list_organization_memberships()
        finally:
            await workos.close()

    @pytest.mark.asyncio
    async def test_list_organization_memberships_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.organization_membership.list_organization_memberships()
        finally:
            await workos.close()
