# This file was auto-generated by Fern from our API Definition.

import datetime as dt
import typing
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.jsonable_encoder import jsonable_encoder
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.change_log_list_response import ChangeLogListResponse

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class RawCrewManagementAdminClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def export_csv(
        self,
        organization_id: str,
        *,
        search_term: typing.Optional[str] = OMIT,
        role_id: typing.Optional[str] = OMIT,
        status_id: typing.Optional[str] = OMIT,
        include_deleted: typing.Optional[bool] = OMIT,
        sort_by: typing.Optional[str] = OMIT,
        sort_order: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.Any]:
        """
        Export organization members as CSV file.

        Requires:
        - User must be authenticated
        - User must be a member of the organization
        - User must have Admin or Owner role
        - Export limited to 10,000 records

        Args:
            organization_id: Organization ID
            request: Export filters
            db: Database session
            auth: Authenticated user

        Returns:
            CSV file as downloadable response

        Raises:
            ValidationException: If export exceeds 10,000 records

        Parameters
        ----------
        organization_id : str
            Organization ID

        search_term : typing.Optional[str]
            Search across full_name, email, and username

        role_id : typing.Optional[str]
            Filter by role ID

        status_id : typing.Optional[str]
            Filter by status ID

        include_deleted : typing.Optional[bool]
            Include soft-deleted members

        sort_by : typing.Optional[str]
            Field to sort by (full_name, email, role_name, status_name, joined_at)

        sort_order : typing.Optional[str]
            Sort order (asc or desc)

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[typing.Any]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(organization_id)}/users/export-csv",
            method="POST",
            json={
                "search_term": search_term,
                "role_id": role_id,
                "status_id": status_id,
                "include_deleted": include_deleted,
                "sort_by": sort_by,
                "sort_order": sort_order,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if _response is None or not _response.text.strip():
                return HttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Any,
                    parse_obj_as(
                        type_=typing.Any,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def export_pdf(
        self,
        organization_id: str,
        *,
        search_term: typing.Optional[str] = OMIT,
        role_id: typing.Optional[str] = OMIT,
        status_id: typing.Optional[str] = OMIT,
        include_deleted: typing.Optional[bool] = OMIT,
        sort_by: typing.Optional[str] = OMIT,
        sort_order: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.Any]:
        """
        Export organization members as PDF file.

        Requires:
        - User must be authenticated
        - User must be a member of the organization
        - User must have Admin or Owner role
        - Export limited to 10,000 records

        Args:
            organization_id: Organization ID
            request: Export filters
            db: Database session
            auth: Authenticated user

        Returns:
            PDF file as downloadable response

        Raises:
            ValidationException: If export exceeds 10,000 records

        Parameters
        ----------
        organization_id : str
            Organization ID

        search_term : typing.Optional[str]
            Search across full_name, email, and username

        role_id : typing.Optional[str]
            Filter by role ID

        status_id : typing.Optional[str]
            Filter by status ID

        include_deleted : typing.Optional[bool]
            Include soft-deleted members

        sort_by : typing.Optional[str]
            Field to sort by (full_name, email, role_name, status_name, joined_at)

        sort_order : typing.Optional[str]
            Sort order (asc or desc)

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[typing.Any]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(organization_id)}/users/export-pdf",
            method="POST",
            json={
                "search_term": search_term,
                "role_id": role_id,
                "status_id": status_id,
                "include_deleted": include_deleted,
                "sort_by": sort_by,
                "sort_order": sort_order,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if _response is None or not _response.text.strip():
                return HttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Any,
                    parse_obj_as(
                        type_=typing.Any,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get_organization_change_logs(
        self,
        organization_id: str,
        *,
        skip: typing.Optional[int] = OMIT,
        take: typing.Optional[int] = OMIT,
        start_date: typing.Optional[dt.datetime] = OMIT,
        end_date: typing.Optional[dt.datetime] = OMIT,
        resource_type: typing.Optional[str] = OMIT,
        action: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ChangeLogListResponse]:
        """
        Get paginated change logs for the organization.

        Requires:
        - User must be authenticated
        - User must be a member of the organization
        - User must have Admin or Owner role

        Args:
            organization_id: Organization ID
            request: Pagination and filter parameters
            db: Database session
            auth: Authenticated user

        Returns:
            Paginated list of audit logs for the organization

        Parameters
        ----------
        organization_id : str
            Organization ID

        skip : typing.Optional[int]
            Number of records to skip

        take : typing.Optional[int]
            Number of records to return (max 100)

        start_date : typing.Optional[dt.datetime]
            Filter logs from this date

        end_date : typing.Optional[dt.datetime]
            Filter logs until this date

        resource_type : typing.Optional[str]
            Filter by resource type (e.g., 'organization_user', 'assistant', 'rule', 'document')

        action : typing.Optional[str]
            Filter by action (e.g., 'created', 'updated', 'deleted', 'added', 'removed')

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ChangeLogListResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(organization_id)}/dashboard/change-logs",
            method="POST",
            json={
                "skip": skip,
                "take": take,
                "start_date": start_date,
                "end_date": end_date,
                "resource_type": resource_type,
                "action": action,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ChangeLogListResponse,
                    parse_obj_as(
                        type_=ChangeLogListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get_member_change_logs(
        self,
        organization_id: str,
        user_id: str,
        *,
        skip: typing.Optional[int] = OMIT,
        take: typing.Optional[int] = OMIT,
        start_date: typing.Optional[dt.datetime] = OMIT,
        end_date: typing.Optional[dt.datetime] = OMIT,
        resource_type: typing.Optional[str] = OMIT,
        action: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ChangeLogListResponse]:
        """
        Get paginated change logs for a specific member.

        Requires:
        - User must be authenticated
        - User must be a member of the organization
        - User must have Admin or Owner role
        - Target user must exist and be a member of the organization

        Args:
            organization_id: Organization ID
            user_id: User ID to get change logs for
            request: Pagination and filter parameters
            db: Database session
            auth: Authenticated user

        Returns:
            Paginated list of audit logs for the specific member

        Raises:
            ResourceNotFoundException: If target user is not found in organization

        Parameters
        ----------
        organization_id : str
            Organization ID

        user_id : str
            User ID to get change logs for

        skip : typing.Optional[int]
            Number of records to skip

        take : typing.Optional[int]
            Number of records to return (max 100)

        start_date : typing.Optional[dt.datetime]
            Filter logs from this date

        end_date : typing.Optional[dt.datetime]
            Filter logs until this date

        resource_type : typing.Optional[str]
            Filter by resource type (e.g., 'organization_user', 'assistant', 'rule', 'document')

        action : typing.Optional[str]
            Filter by action (e.g., 'created', 'updated', 'deleted', 'added', 'removed')

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ChangeLogListResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(organization_id)}/users/{jsonable_encoder(user_id)}/change-logs",
            method="POST",
            json={
                "skip": skip,
                "take": take,
                "start_date": start_date,
                "end_date": end_date,
                "resource_type": resource_type,
                "action": action,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ChangeLogListResponse,
                    parse_obj_as(
                        type_=ChangeLogListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawCrewManagementAdminClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def export_csv(
        self,
        organization_id: str,
        *,
        search_term: typing.Optional[str] = OMIT,
        role_id: typing.Optional[str] = OMIT,
        status_id: typing.Optional[str] = OMIT,
        include_deleted: typing.Optional[bool] = OMIT,
        sort_by: typing.Optional[str] = OMIT,
        sort_order: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.Any]:
        """
        Export organization members as CSV file.

        Requires:
        - User must be authenticated
        - User must be a member of the organization
        - User must have Admin or Owner role
        - Export limited to 10,000 records

        Args:
            organization_id: Organization ID
            request: Export filters
            db: Database session
            auth: Authenticated user

        Returns:
            CSV file as downloadable response

        Raises:
            ValidationException: If export exceeds 10,000 records

        Parameters
        ----------
        organization_id : str
            Organization ID

        search_term : typing.Optional[str]
            Search across full_name, email, and username

        role_id : typing.Optional[str]
            Filter by role ID

        status_id : typing.Optional[str]
            Filter by status ID

        include_deleted : typing.Optional[bool]
            Include soft-deleted members

        sort_by : typing.Optional[str]
            Field to sort by (full_name, email, role_name, status_name, joined_at)

        sort_order : typing.Optional[str]
            Sort order (asc or desc)

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[typing.Any]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(organization_id)}/users/export-csv",
            method="POST",
            json={
                "search_term": search_term,
                "role_id": role_id,
                "status_id": status_id,
                "include_deleted": include_deleted,
                "sort_by": sort_by,
                "sort_order": sort_order,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if _response is None or not _response.text.strip():
                return AsyncHttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Any,
                    parse_obj_as(
                        type_=typing.Any,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def export_pdf(
        self,
        organization_id: str,
        *,
        search_term: typing.Optional[str] = OMIT,
        role_id: typing.Optional[str] = OMIT,
        status_id: typing.Optional[str] = OMIT,
        include_deleted: typing.Optional[bool] = OMIT,
        sort_by: typing.Optional[str] = OMIT,
        sort_order: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.Any]:
        """
        Export organization members as PDF file.

        Requires:
        - User must be authenticated
        - User must be a member of the organization
        - User must have Admin or Owner role
        - Export limited to 10,000 records

        Args:
            organization_id: Organization ID
            request: Export filters
            db: Database session
            auth: Authenticated user

        Returns:
            PDF file as downloadable response

        Raises:
            ValidationException: If export exceeds 10,000 records

        Parameters
        ----------
        organization_id : str
            Organization ID

        search_term : typing.Optional[str]
            Search across full_name, email, and username

        role_id : typing.Optional[str]
            Filter by role ID

        status_id : typing.Optional[str]
            Filter by status ID

        include_deleted : typing.Optional[bool]
            Include soft-deleted members

        sort_by : typing.Optional[str]
            Field to sort by (full_name, email, role_name, status_name, joined_at)

        sort_order : typing.Optional[str]
            Sort order (asc or desc)

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[typing.Any]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(organization_id)}/users/export-pdf",
            method="POST",
            json={
                "search_term": search_term,
                "role_id": role_id,
                "status_id": status_id,
                "include_deleted": include_deleted,
                "sort_by": sort_by,
                "sort_order": sort_order,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if _response is None or not _response.text.strip():
                return AsyncHttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Any,
                    parse_obj_as(
                        type_=typing.Any,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get_organization_change_logs(
        self,
        organization_id: str,
        *,
        skip: typing.Optional[int] = OMIT,
        take: typing.Optional[int] = OMIT,
        start_date: typing.Optional[dt.datetime] = OMIT,
        end_date: typing.Optional[dt.datetime] = OMIT,
        resource_type: typing.Optional[str] = OMIT,
        action: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ChangeLogListResponse]:
        """
        Get paginated change logs for the organization.

        Requires:
        - User must be authenticated
        - User must be a member of the organization
        - User must have Admin or Owner role

        Args:
            organization_id: Organization ID
            request: Pagination and filter parameters
            db: Database session
            auth: Authenticated user

        Returns:
            Paginated list of audit logs for the organization

        Parameters
        ----------
        organization_id : str
            Organization ID

        skip : typing.Optional[int]
            Number of records to skip

        take : typing.Optional[int]
            Number of records to return (max 100)

        start_date : typing.Optional[dt.datetime]
            Filter logs from this date

        end_date : typing.Optional[dt.datetime]
            Filter logs until this date

        resource_type : typing.Optional[str]
            Filter by resource type (e.g., 'organization_user', 'assistant', 'rule', 'document')

        action : typing.Optional[str]
            Filter by action (e.g., 'created', 'updated', 'deleted', 'added', 'removed')

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ChangeLogListResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(organization_id)}/dashboard/change-logs",
            method="POST",
            json={
                "skip": skip,
                "take": take,
                "start_date": start_date,
                "end_date": end_date,
                "resource_type": resource_type,
                "action": action,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ChangeLogListResponse,
                    parse_obj_as(
                        type_=ChangeLogListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get_member_change_logs(
        self,
        organization_id: str,
        user_id: str,
        *,
        skip: typing.Optional[int] = OMIT,
        take: typing.Optional[int] = OMIT,
        start_date: typing.Optional[dt.datetime] = OMIT,
        end_date: typing.Optional[dt.datetime] = OMIT,
        resource_type: typing.Optional[str] = OMIT,
        action: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ChangeLogListResponse]:
        """
        Get paginated change logs for a specific member.

        Requires:
        - User must be authenticated
        - User must be a member of the organization
        - User must have Admin or Owner role
        - Target user must exist and be a member of the organization

        Args:
            organization_id: Organization ID
            user_id: User ID to get change logs for
            request: Pagination and filter parameters
            db: Database session
            auth: Authenticated user

        Returns:
            Paginated list of audit logs for the specific member

        Raises:
            ResourceNotFoundException: If target user is not found in organization

        Parameters
        ----------
        organization_id : str
            Organization ID

        user_id : str
            User ID to get change logs for

        skip : typing.Optional[int]
            Number of records to skip

        take : typing.Optional[int]
            Number of records to return (max 100)

        start_date : typing.Optional[dt.datetime]
            Filter logs from this date

        end_date : typing.Optional[dt.datetime]
            Filter logs until this date

        resource_type : typing.Optional[str]
            Filter by resource type (e.g., 'organization_user', 'assistant', 'rule', 'document')

        action : typing.Optional[str]
            Filter by action (e.g., 'created', 'updated', 'deleted', 'added', 'removed')

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ChangeLogListResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/organizations/{jsonable_encoder(organization_id)}/users/{jsonable_encoder(user_id)}/change-logs",
            method="POST",
            json={
                "skip": skip,
                "take": take,
                "start_date": start_date,
                "end_date": end_date,
                "resource_type": resource_type,
                "action": action,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ChangeLogListResponse,
                    parse_obj_as(
                        type_=ChangeLogListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
