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

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 ..core.serialization import convert_and_respect_annotation_metadata
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.http_validation_error import HttpValidationError
from ..types.schedule_config import ScheduleConfig
from ..types.source_connection import SourceConnection
from ..types.source_connection_job import SourceConnectionJob
from ..types.source_connection_list_item import SourceConnectionListItem
from .types.authentication import Authentication

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


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

    def list(
        self,
        *,
        collection: typing.Optional[str] = None,
        skip: typing.Optional[int] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.List[SourceConnectionListItem]]:
        """
        List source connections with minimal fields for performance.

        Parameters
        ----------
        collection : typing.Optional[str]
            Filter by collection readable ID

        skip : typing.Optional[int]

        limit : typing.Optional[int]

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

        Returns
        -------
        HttpResponse[typing.List[SourceConnectionListItem]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "source-connections",
            method="GET",
            params={
                "collection": collection,
                "skip": skip,
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[SourceConnectionListItem],
                    parse_obj_as(
                        type_=typing.List[SourceConnectionListItem],  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 create(
        self,
        *,
        short_name: str,
        readable_collection_id: str,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        config: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        schedule: typing.Optional[ScheduleConfig] = OMIT,
        sync_immediately: typing.Optional[bool] = OMIT,
        authentication: typing.Optional[Authentication] = OMIT,
        redirect_url: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[SourceConnection]:
        """
        Create a new source connection.

        The authentication configuration determines the flow:
        - DirectAuthentication: Immediate creation with provided credentials
        - OAuthBrowserAuthentication: Returns shell with authentication URL
        - OAuthTokenAuthentication: Immediate creation with provided token
        - AuthProviderAuthentication: Using external auth provider

        BYOC (Bring Your Own Client) is detected when client_id and client_secret
        are provided in OAuthBrowserAuthentication.

        sync_immediately defaults:
        - True for: direct, oauth_token, auth_provider
        - False for: oauth_browser, oauth_byoc (these sync after authentication)

        Parameters
        ----------
        short_name : str
            Source identifier (e.g., 'slack', 'github')

        readable_collection_id : str
            Collection readable ID

        name : typing.Optional[str]
            Connection name (defaults to '{Source Name} Connection')

        description : typing.Optional[str]
            Connection description

        config : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Source-specific configuration

        schedule : typing.Optional[ScheduleConfig]

        sync_immediately : typing.Optional[bool]
            Run initial sync after creation. Defaults to True for direct/token/auth_provider, False for OAuth browser/BYOC flows (which sync after authentication)

        authentication : typing.Optional[Authentication]
            Authentication config (defaults to OAuth browser flow for OAuth sources)

        redirect_url : typing.Optional[str]
            URL to redirect to after OAuth flow completes (only used for OAuth flows)

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

        Returns
        -------
        HttpResponse[SourceConnection]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "source-connections",
            method="POST",
            json={
                "name": name,
                "short_name": short_name,
                "readable_collection_id": readable_collection_id,
                "description": description,
                "config": config,
                "schedule": convert_and_respect_annotation_metadata(
                    object_=schedule, annotation=ScheduleConfig, direction="write"
                ),
                "sync_immediately": sync_immediately,
                "authentication": convert_and_respect_annotation_metadata(
                    object_=authentication, annotation=Authentication, direction="write"
                ),
                "redirect_url": redirect_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SourceConnection,
                    parse_obj_as(
                        type_=SourceConnection,  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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(
        self, source_connection_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[SourceConnection]:
        """
        Get a source connection with optional depth expansion.

        Parameters
        ----------
        source_connection_id : str

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

        Returns
        -------
        HttpResponse[SourceConnection]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"source-connections/{jsonable_encoder(source_connection_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SourceConnection,
                    parse_obj_as(
                        type_=SourceConnection,  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 delete(
        self, source_connection_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[SourceConnection]:
        """
        Delete a source connection and all related data.

        Parameters
        ----------
        source_connection_id : str

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

        Returns
        -------
        HttpResponse[SourceConnection]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"source-connections/{jsonable_encoder(source_connection_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SourceConnection,
                    parse_obj_as(
                        type_=SourceConnection,  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 update(
        self,
        source_connection_id: str,
        *,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        config: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        schedule: typing.Optional[ScheduleConfig] = OMIT,
        authentication: typing.Optional[Authentication] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[SourceConnection]:
        """
        Update a source connection.

        Updateable fields:
        - name, description
        - config_fields
        - cron_schedule
        - auth_fields (direct auth only)

        Parameters
        ----------
        source_connection_id : str

        name : typing.Optional[str]

        description : typing.Optional[str]

        config : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Source-specific configuration

        schedule : typing.Optional[ScheduleConfig]

        authentication : typing.Optional[Authentication]
            Authentication config (defaults to OAuth browser flow for OAuth sources)

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

        Returns
        -------
        HttpResponse[SourceConnection]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"source-connections/{jsonable_encoder(source_connection_id)}",
            method="PATCH",
            json={
                "name": name,
                "description": description,
                "config": config,
                "schedule": convert_and_respect_annotation_metadata(
                    object_=schedule, annotation=ScheduleConfig, direction="write"
                ),
                "authentication": convert_and_respect_annotation_metadata(
                    object_=authentication, annotation=Authentication, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SourceConnection,
                    parse_obj_as(
                        type_=SourceConnection,  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 run(
        self,
        source_connection_id: str,
        *,
        force_full_sync: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[SourceConnectionJob]:
        """
        Trigger a sync run for a source connection.

        Runs are always executed through Temporal workflow engine.

        Args:
            db: Database session
            source_connection_id: ID of the source connection to run
            ctx: API context with organization and user information
            guard_rail: Guard rail service for usage limits
            force_full_sync: If True, forces a full sync with orphaned entity cleanup
                            for continuous syncs. Raises 400 error if used on
                            non-continuous syncs (which are always full syncs).

        Parameters
        ----------
        source_connection_id : str

        force_full_sync : typing.Optional[bool]
            Force a full sync ignoring cursor data instead of waiting for the daily cleanup schedule. Only allowed for continuous syncs.

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

        Returns
        -------
        HttpResponse[SourceConnectionJob]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"source-connections/{jsonable_encoder(source_connection_id)}/run",
            method="POST",
            params={
                "force_full_sync": force_full_sync,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SourceConnectionJob,
                    parse_obj_as(
                        type_=SourceConnectionJob,  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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_source_connection_jobs(
        self,
        source_connection_id: str,
        *,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.List[SourceConnectionJob]]:
        """
        Get sync jobs for a source connection.

        Parameters
        ----------
        source_connection_id : str

        limit : typing.Optional[int]

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

        Returns
        -------
        HttpResponse[typing.List[SourceConnectionJob]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"source-connections/{jsonable_encoder(source_connection_id)}/jobs",
            method="GET",
            params={
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[SourceConnectionJob],
                    parse_obj_as(
                        type_=typing.List[SourceConnectionJob],  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 cancel_job(
        self, source_connection_id: str, job_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[SourceConnectionJob]:
        """
        Cancel a running sync job for a source connection.

        This endpoint requests cancellation and marks the job as CANCELLING.
        The workflow updates the final status to CANCELLED when it processes
        the cancellation request.

        Parameters
        ----------
        source_connection_id : str

        job_id : str

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

        Returns
        -------
        HttpResponse[SourceConnectionJob]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"source-connections/{jsonable_encoder(source_connection_id)}/jobs/{jsonable_encoder(job_id)}/cancel",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SourceConnectionJob,
                    parse_obj_as(
                        type_=SourceConnectionJob,  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 AsyncRawSourceConnectionsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list(
        self,
        *,
        collection: typing.Optional[str] = None,
        skip: typing.Optional[int] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.List[SourceConnectionListItem]]:
        """
        List source connections with minimal fields for performance.

        Parameters
        ----------
        collection : typing.Optional[str]
            Filter by collection readable ID

        skip : typing.Optional[int]

        limit : typing.Optional[int]

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

        Returns
        -------
        AsyncHttpResponse[typing.List[SourceConnectionListItem]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "source-connections",
            method="GET",
            params={
                "collection": collection,
                "skip": skip,
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[SourceConnectionListItem],
                    parse_obj_as(
                        type_=typing.List[SourceConnectionListItem],  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 create(
        self,
        *,
        short_name: str,
        readable_collection_id: str,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        config: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        schedule: typing.Optional[ScheduleConfig] = OMIT,
        sync_immediately: typing.Optional[bool] = OMIT,
        authentication: typing.Optional[Authentication] = OMIT,
        redirect_url: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[SourceConnection]:
        """
        Create a new source connection.

        The authentication configuration determines the flow:
        - DirectAuthentication: Immediate creation with provided credentials
        - OAuthBrowserAuthentication: Returns shell with authentication URL
        - OAuthTokenAuthentication: Immediate creation with provided token
        - AuthProviderAuthentication: Using external auth provider

        BYOC (Bring Your Own Client) is detected when client_id and client_secret
        are provided in OAuthBrowserAuthentication.

        sync_immediately defaults:
        - True for: direct, oauth_token, auth_provider
        - False for: oauth_browser, oauth_byoc (these sync after authentication)

        Parameters
        ----------
        short_name : str
            Source identifier (e.g., 'slack', 'github')

        readable_collection_id : str
            Collection readable ID

        name : typing.Optional[str]
            Connection name (defaults to '{Source Name} Connection')

        description : typing.Optional[str]
            Connection description

        config : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Source-specific configuration

        schedule : typing.Optional[ScheduleConfig]

        sync_immediately : typing.Optional[bool]
            Run initial sync after creation. Defaults to True for direct/token/auth_provider, False for OAuth browser/BYOC flows (which sync after authentication)

        authentication : typing.Optional[Authentication]
            Authentication config (defaults to OAuth browser flow for OAuth sources)

        redirect_url : typing.Optional[str]
            URL to redirect to after OAuth flow completes (only used for OAuth flows)

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

        Returns
        -------
        AsyncHttpResponse[SourceConnection]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "source-connections",
            method="POST",
            json={
                "name": name,
                "short_name": short_name,
                "readable_collection_id": readable_collection_id,
                "description": description,
                "config": config,
                "schedule": convert_and_respect_annotation_metadata(
                    object_=schedule, annotation=ScheduleConfig, direction="write"
                ),
                "sync_immediately": sync_immediately,
                "authentication": convert_and_respect_annotation_metadata(
                    object_=authentication, annotation=Authentication, direction="write"
                ),
                "redirect_url": redirect_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SourceConnection,
                    parse_obj_as(
                        type_=SourceConnection,  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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(
        self, source_connection_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[SourceConnection]:
        """
        Get a source connection with optional depth expansion.

        Parameters
        ----------
        source_connection_id : str

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

        Returns
        -------
        AsyncHttpResponse[SourceConnection]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"source-connections/{jsonable_encoder(source_connection_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SourceConnection,
                    parse_obj_as(
                        type_=SourceConnection,  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 delete(
        self, source_connection_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[SourceConnection]:
        """
        Delete a source connection and all related data.

        Parameters
        ----------
        source_connection_id : str

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

        Returns
        -------
        AsyncHttpResponse[SourceConnection]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"source-connections/{jsonable_encoder(source_connection_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SourceConnection,
                    parse_obj_as(
                        type_=SourceConnection,  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 update(
        self,
        source_connection_id: str,
        *,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        config: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        schedule: typing.Optional[ScheduleConfig] = OMIT,
        authentication: typing.Optional[Authentication] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[SourceConnection]:
        """
        Update a source connection.

        Updateable fields:
        - name, description
        - config_fields
        - cron_schedule
        - auth_fields (direct auth only)

        Parameters
        ----------
        source_connection_id : str

        name : typing.Optional[str]

        description : typing.Optional[str]

        config : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Source-specific configuration

        schedule : typing.Optional[ScheduleConfig]

        authentication : typing.Optional[Authentication]
            Authentication config (defaults to OAuth browser flow for OAuth sources)

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

        Returns
        -------
        AsyncHttpResponse[SourceConnection]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"source-connections/{jsonable_encoder(source_connection_id)}",
            method="PATCH",
            json={
                "name": name,
                "description": description,
                "config": config,
                "schedule": convert_and_respect_annotation_metadata(
                    object_=schedule, annotation=ScheduleConfig, direction="write"
                ),
                "authentication": convert_and_respect_annotation_metadata(
                    object_=authentication, annotation=Authentication, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SourceConnection,
                    parse_obj_as(
                        type_=SourceConnection,  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 run(
        self,
        source_connection_id: str,
        *,
        force_full_sync: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[SourceConnectionJob]:
        """
        Trigger a sync run for a source connection.

        Runs are always executed through Temporal workflow engine.

        Args:
            db: Database session
            source_connection_id: ID of the source connection to run
            ctx: API context with organization and user information
            guard_rail: Guard rail service for usage limits
            force_full_sync: If True, forces a full sync with orphaned entity cleanup
                            for continuous syncs. Raises 400 error if used on
                            non-continuous syncs (which are always full syncs).

        Parameters
        ----------
        source_connection_id : str

        force_full_sync : typing.Optional[bool]
            Force a full sync ignoring cursor data instead of waiting for the daily cleanup schedule. Only allowed for continuous syncs.

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

        Returns
        -------
        AsyncHttpResponse[SourceConnectionJob]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"source-connections/{jsonable_encoder(source_connection_id)}/run",
            method="POST",
            params={
                "force_full_sync": force_full_sync,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SourceConnectionJob,
                    parse_obj_as(
                        type_=SourceConnectionJob,  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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_source_connection_jobs(
        self,
        source_connection_id: str,
        *,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.List[SourceConnectionJob]]:
        """
        Get sync jobs for a source connection.

        Parameters
        ----------
        source_connection_id : str

        limit : typing.Optional[int]

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

        Returns
        -------
        AsyncHttpResponse[typing.List[SourceConnectionJob]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"source-connections/{jsonable_encoder(source_connection_id)}/jobs",
            method="GET",
            params={
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[SourceConnectionJob],
                    parse_obj_as(
                        type_=typing.List[SourceConnectionJob],  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 cancel_job(
        self, source_connection_id: str, job_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[SourceConnectionJob]:
        """
        Cancel a running sync job for a source connection.

        This endpoint requests cancellation and marks the job as CANCELLING.
        The workflow updates the final status to CANCELLED when it processes
        the cancellation request.

        Parameters
        ----------
        source_connection_id : str

        job_id : str

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

        Returns
        -------
        AsyncHttpResponse[SourceConnectionJob]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"source-connections/{jsonable_encoder(source_connection_id)}/jobs/{jsonable_encoder(job_id)}/cancel",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SourceConnectionJob,
                    parse_obj_as(
                        type_=SourceConnectionJob,  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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)
