# 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.request_options import RequestOptions
from ..core.unchecked_base_model import construct_type
from ..errors.not_found_error import NotFoundError
from .types.data_export import DataExport
from .types.data_export_export_reporting_data_response import DataExportExportReportingDataResponse

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


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

    def export_reporting_data(
        self,
        job_identifier: str,
        *,
        app_id: str,
        client_id: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[DataExportExportReportingDataResponse]:
        """
        Parameters
        ----------
        job_identifier : str
            Unique identifier of the job.

        app_id : str
            The Intercom defined code of the workspace the company is associated to.

        client_id : str

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

        Returns
        -------
        HttpResponse[DataExportExportReportingDataResponse]
            Job status returned successfully
        """
        _response = self._client_wrapper.httpx_client.request(
            f"export/reporting_data/{jsonable_encoder(job_identifier)}",
            method="GET",
            params={
                "app_id": app_id,
                "client_id": client_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DataExportExportReportingDataResponse,
                    construct_type(
                        type_=DataExportExportReportingDataResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 download_reporting_data_export(
        self, job_identifier: str, *, app_id: str, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[None]:
        """
        Download the data from a completed reporting data export job.

        > Octet header required
        >
        > You will have to specify the header Accept: `application/octet-stream` when hitting this endpoint.

        Parameters
        ----------
        job_identifier : str

        app_id : str

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"download/reporting_data/{jsonable_encoder(job_identifier)}",
            method="GET",
            params={
                "app_id": app_id,
            },
            headers={
                "Accept": "application/octet-stream",
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 create(
        self, *, created_at_after: int, created_at_before: int, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[DataExport]:
        """
        To create your export job, you need to send a `POST` request to the export endpoint `https://api.intercom.io/export/content/data`.

        The only parameters you need to provide are the range of dates that you want exported.

        >🚧 Limit of one active job
        >
        > You can only have one active job per workspace. You will receive a HTTP status code of 429 with the message Exceeded rate limit of 1 pending message data export jobs if you attempt to create a second concurrent job.

        >❗️ Updated_at not included
        >
        > It should be noted that the timeframe only includes messages sent during the time period and not messages that were only updated during this period. For example, if a message was updated yesterday but sent two days ago, you would need to set the created_at_after date before the message was sent to include that in your retrieval job.

        >📘 Date ranges are inclusive
        >
        > Requesting data for 2018-06-01 until 2018-06-30 will get all data for those days including those specified - e.g. 2018-06-01 00:00:00 until 2018-06-30 23:59:99.

        Parameters
        ----------
        created_at_after : int
            The start date that you request data for. It must be formatted as a unix timestamp.

        created_at_before : int
            The end date that you request data for. It must be formatted as a unix timestamp.

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

        Returns
        -------
        HttpResponse[DataExport]
            successful
        """
        _response = self._client_wrapper.httpx_client.request(
            "export/content/data",
            method="POST",
            json={
                "created_at_after": created_at_after,
                "created_at_before": created_at_before,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DataExport,
                    construct_type(
                        type_=DataExport,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _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 find(
        self, job_identifier: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[DataExport]:
        """
        You can view the status of your job by sending a `GET` request to the URL
        `https://api.intercom.io/export/content/data/{job_identifier}` - the `{job_identifier}` is the value returned in the response when you first created the export job. More on it can be seen in the Export Job Model.

        > 🚧 Jobs expire after two days
        > All jobs that have completed processing (and are thus available to download from the provided URL) will have an expiry limit of two days from when the export ob completed. After this, the data will no longer be available.

        Parameters
        ----------
        job_identifier : str
            job_identifier

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

        Returns
        -------
        HttpResponse[DataExport]
            successful
        """
        _response = self._client_wrapper.httpx_client.request(
            f"export/content/data/{jsonable_encoder(job_identifier)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DataExport,
                    construct_type(
                        type_=DataExport,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _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(
        self, job_identifier: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[DataExport]:
        """
        You can cancel your job

        Parameters
        ----------
        job_identifier : str
            job_identifier

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

        Returns
        -------
        HttpResponse[DataExport]
            successful
        """
        _response = self._client_wrapper.httpx_client.request(
            f"export/cancel/{jsonable_encoder(job_identifier)}",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DataExport,
                    construct_type(
                        type_=DataExport,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _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 download(
        self, job_identifier: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[None]:
        """
        When a job has a status of complete, and thus a filled download_url, you can download your data by hitting that provided URL, formatted like so: https://api.intercom.io/download/content/data/xyz1234.

        Your exported message data will be streamed continuously back down to you in a gzipped CSV format.

        > 📘 Octet header required
        >
        > You will have to specify the header Accept: `application/octet-stream` when hitting this endpoint.

        Parameters
        ----------
        job_identifier : str
            job_identifier

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"download/content/data/{jsonable_encoder(job_identifier)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            _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 AsyncRawDataExportClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def export_reporting_data(
        self,
        job_identifier: str,
        *,
        app_id: str,
        client_id: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[DataExportExportReportingDataResponse]:
        """
        Parameters
        ----------
        job_identifier : str
            Unique identifier of the job.

        app_id : str
            The Intercom defined code of the workspace the company is associated to.

        client_id : str

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

        Returns
        -------
        AsyncHttpResponse[DataExportExportReportingDataResponse]
            Job status returned successfully
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"export/reporting_data/{jsonable_encoder(job_identifier)}",
            method="GET",
            params={
                "app_id": app_id,
                "client_id": client_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DataExportExportReportingDataResponse,
                    construct_type(
                        type_=DataExportExportReportingDataResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 download_reporting_data_export(
        self, job_identifier: str, *, app_id: str, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[None]:
        """
        Download the data from a completed reporting data export job.

        > Octet header required
        >
        > You will have to specify the header Accept: `application/octet-stream` when hitting this endpoint.

        Parameters
        ----------
        job_identifier : str

        app_id : str

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"download/reporting_data/{jsonable_encoder(job_identifier)}",
            method="GET",
            params={
                "app_id": app_id,
            },
            headers={
                "Accept": "application/octet-stream",
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 create(
        self, *, created_at_after: int, created_at_before: int, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[DataExport]:
        """
        To create your export job, you need to send a `POST` request to the export endpoint `https://api.intercom.io/export/content/data`.

        The only parameters you need to provide are the range of dates that you want exported.

        >🚧 Limit of one active job
        >
        > You can only have one active job per workspace. You will receive a HTTP status code of 429 with the message Exceeded rate limit of 1 pending message data export jobs if you attempt to create a second concurrent job.

        >❗️ Updated_at not included
        >
        > It should be noted that the timeframe only includes messages sent during the time period and not messages that were only updated during this period. For example, if a message was updated yesterday but sent two days ago, you would need to set the created_at_after date before the message was sent to include that in your retrieval job.

        >📘 Date ranges are inclusive
        >
        > Requesting data for 2018-06-01 until 2018-06-30 will get all data for those days including those specified - e.g. 2018-06-01 00:00:00 until 2018-06-30 23:59:99.

        Parameters
        ----------
        created_at_after : int
            The start date that you request data for. It must be formatted as a unix timestamp.

        created_at_before : int
            The end date that you request data for. It must be formatted as a unix timestamp.

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

        Returns
        -------
        AsyncHttpResponse[DataExport]
            successful
        """
        _response = await self._client_wrapper.httpx_client.request(
            "export/content/data",
            method="POST",
            json={
                "created_at_after": created_at_after,
                "created_at_before": created_at_before,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DataExport,
                    construct_type(
                        type_=DataExport,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _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 find(
        self, job_identifier: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[DataExport]:
        """
        You can view the status of your job by sending a `GET` request to the URL
        `https://api.intercom.io/export/content/data/{job_identifier}` - the `{job_identifier}` is the value returned in the response when you first created the export job. More on it can be seen in the Export Job Model.

        > 🚧 Jobs expire after two days
        > All jobs that have completed processing (and are thus available to download from the provided URL) will have an expiry limit of two days from when the export ob completed. After this, the data will no longer be available.

        Parameters
        ----------
        job_identifier : str
            job_identifier

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

        Returns
        -------
        AsyncHttpResponse[DataExport]
            successful
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"export/content/data/{jsonable_encoder(job_identifier)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DataExport,
                    construct_type(
                        type_=DataExport,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _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(
        self, job_identifier: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[DataExport]:
        """
        You can cancel your job

        Parameters
        ----------
        job_identifier : str
            job_identifier

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

        Returns
        -------
        AsyncHttpResponse[DataExport]
            successful
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"export/cancel/{jsonable_encoder(job_identifier)}",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DataExport,
                    construct_type(
                        type_=DataExport,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _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 download(
        self, job_identifier: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[None]:
        """
        When a job has a status of complete, and thus a filled download_url, you can download your data by hitting that provided URL, formatted like so: https://api.intercom.io/download/content/data/xyz1234.

        Your exported message data will be streamed continuously back down to you in a gzipped CSV format.

        > 📘 Octet header required
        >
        > You will have to specify the header Accept: `application/octet-stream` when hitting this endpoint.

        Parameters
        ----------
        job_identifier : str
            job_identifier

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"download/content/data/{jsonable_encoder(job_identifier)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            _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)
