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

import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js";
import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js";
import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js";
import * as core from "../../../../core/index.js";
import * as environments from "../../../../environments.js";
import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js";
import * as errors from "../../../../errors/index.js";
import * as Intercom from "../../../index.js";

export declare namespace DataExportClient {
    export interface Options extends BaseClientOptions {}

    export interface RequestOptions extends BaseRequestOptions {}
}

/**
 * Everything about your Data Exports
 */
export class DataExportClient {
    protected readonly _options: NormalizedClientOptionsWithAuth<DataExportClient.Options>;

    constructor(options: DataExportClient.Options = {}) {
        this._options = normalizeClientOptionsWithAuth(options);
    }

    /**
     * @param {Intercom.ExportReportingDataRequest} request
     * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.dataExport.exportReportingData({
     *         job_identifier: "job_identifier",
     *         app_id: "app_id",
     *         client_id: "client_id"
     *     })
     */
    public exportReportingData(
        request: Intercom.ExportReportingDataRequest,
        requestOptions?: DataExportClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.DataExportExportReportingDataResponse> {
        return core.HttpResponsePromise.fromPromise(this.__exportReportingData(request, requestOptions));
    }

    private async __exportReportingData(
        request: Intercom.ExportReportingDataRequest,
        requestOptions?: DataExportClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.DataExportExportReportingDataResponse>> {
        const { job_identifier: jobIdentifier, app_id: appId, client_id: clientId } = request;
        const _queryParams: Record<string, string | string[] | object | object[] | null> = {};
        _queryParams.app_id = appId;
        _queryParams.client_id = clientId;
        const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
        const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
            _authRequest.headers,
            this._options?.headers,
            mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }),
            requestOptions?.headers,
        );
        const _response = await (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.IntercomEnvironment.UsProduction,
                `export/reporting_data/${core.url.encodePathParam(jobIdentifier)}`,
            ),
            method: "GET",
            headers: _headers,
            queryParameters: { ..._queryParams, ...requestOptions?.queryParams },
            timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000,
            maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
            fetchFn: this._options?.fetch,
            logging: this._options.logging,
        });
        if (_response.ok) {
            return {
                data: _response.body as Intercom.DataExportExportReportingDataResponse,
                rawResponse: _response.rawResponse,
            };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 404:
                    throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse);
                default:
                    throw new errors.IntercomError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

        return handleNonStatusCodeError(
            _response.error,
            _response.rawResponse,
            "GET",
            "/export/reporting_data/{job_identifier}",
        );
    }

    /**
     * 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.
     *
     * @param {Intercom.DownloadReportingDataExportRequest} request
     * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.dataExport.downloadReportingDataExport({
     *         job_identifier: "job_identifier",
     *         app_id: "app_id"
     *     })
     */
    public downloadReportingDataExport(
        request: Intercom.DownloadReportingDataExportRequest,
        requestOptions?: DataExportClient.RequestOptions,
    ): core.HttpResponsePromise<void> {
        return core.HttpResponsePromise.fromPromise(this.__downloadReportingDataExport(request, requestOptions));
    }

    private async __downloadReportingDataExport(
        request: Intercom.DownloadReportingDataExportRequest,
        requestOptions?: DataExportClient.RequestOptions,
    ): Promise<core.WithRawResponse<void>> {
        const { job_identifier: jobIdentifier, app_id: appId } = request;
        const _queryParams: Record<string, string | string[] | object | object[] | null> = {};
        _queryParams.app_id = appId;
        const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
        const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
            _authRequest.headers,
            this._options?.headers,
            mergeOnlyDefinedHeaders({
                Accept: "application/octet-stream",
                "Intercom-Version": requestOptions?.version,
            }),
            requestOptions?.headers,
        );
        const _response = await (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.IntercomEnvironment.UsProduction,
                `download/reporting_data/${core.url.encodePathParam(jobIdentifier)}`,
            ),
            method: "GET",
            headers: _headers,
            queryParameters: { ..._queryParams, ...requestOptions?.queryParams },
            timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000,
            maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
            fetchFn: this._options?.fetch,
            logging: this._options.logging,
        });
        if (_response.ok) {
            return { data: undefined, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 404:
                    throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse);
                default:
                    throw new errors.IntercomError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

        return handleNonStatusCodeError(
            _response.error,
            _response.rawResponse,
            "GET",
            "/download/reporting_data/{job_identifier}",
        );
    }

    /**
     * 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.
     *
     * @param {Intercom.CreateDataExportRequest} request
     * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.dataExport.create({
     *         created_at_after: 1734519776,
     *         created_at_before: 1734537776
     *     })
     */
    public create(
        request: Intercom.CreateDataExportRequest,
        requestOptions?: DataExportClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.DataExport> {
        return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));
    }

    private async __create(
        request: Intercom.CreateDataExportRequest,
        requestOptions?: DataExportClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.DataExport>> {
        const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
        const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
            _authRequest.headers,
            this._options?.headers,
            mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }),
            requestOptions?.headers,
        );
        const _response = await (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.IntercomEnvironment.UsProduction,
                "export/content/data",
            ),
            method: "POST",
            headers: _headers,
            contentType: "application/json",
            queryParameters: requestOptions?.queryParams,
            requestType: "json",
            body: request,
            timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000,
            maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
            fetchFn: this._options?.fetch,
            logging: this._options.logging,
        });
        if (_response.ok) {
            return { data: _response.body as Intercom.DataExport, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            throw new errors.IntercomError({
                statusCode: _response.error.statusCode,
                body: _response.error.body,
                rawResponse: _response.rawResponse,
            });
        }

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/export/content/data");
    }

    /**
     * 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.
     *
     * @param {Intercom.FindDataExportRequest} request
     * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.dataExport.find({
     *         job_identifier: "job_identifier"
     *     })
     */
    public find(
        request: Intercom.FindDataExportRequest,
        requestOptions?: DataExportClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.DataExport> {
        return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions));
    }

    private async __find(
        request: Intercom.FindDataExportRequest,
        requestOptions?: DataExportClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.DataExport>> {
        const { job_identifier: jobIdentifier } = request;
        const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
        const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
            _authRequest.headers,
            this._options?.headers,
            mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }),
            requestOptions?.headers,
        );
        const _response = await (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.IntercomEnvironment.UsProduction,
                `export/content/data/${core.url.encodePathParam(jobIdentifier)}`,
            ),
            method: "GET",
            headers: _headers,
            queryParameters: requestOptions?.queryParams,
            timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000,
            maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
            fetchFn: this._options?.fetch,
            logging: this._options.logging,
        });
        if (_response.ok) {
            return { data: _response.body as Intercom.DataExport, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            throw new errors.IntercomError({
                statusCode: _response.error.statusCode,
                body: _response.error.body,
                rawResponse: _response.rawResponse,
            });
        }

        return handleNonStatusCodeError(
            _response.error,
            _response.rawResponse,
            "GET",
            "/export/content/data/{job_identifier}",
        );
    }

    /**
     * You can cancel your job
     *
     * @param {Intercom.CancelDataExportRequest} request
     * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.dataExport.cancel({
     *         job_identifier: "job_identifier"
     *     })
     */
    public cancel(
        request: Intercom.CancelDataExportRequest,
        requestOptions?: DataExportClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.DataExport> {
        return core.HttpResponsePromise.fromPromise(this.__cancel(request, requestOptions));
    }

    private async __cancel(
        request: Intercom.CancelDataExportRequest,
        requestOptions?: DataExportClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.DataExport>> {
        const { job_identifier: jobIdentifier } = request;
        const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
        const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
            _authRequest.headers,
            this._options?.headers,
            mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }),
            requestOptions?.headers,
        );
        const _response = await (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.IntercomEnvironment.UsProduction,
                `export/cancel/${core.url.encodePathParam(jobIdentifier)}`,
            ),
            method: "POST",
            headers: _headers,
            queryParameters: requestOptions?.queryParams,
            timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000,
            maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
            fetchFn: this._options?.fetch,
            logging: this._options.logging,
        });
        if (_response.ok) {
            return { data: _response.body as Intercom.DataExport, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            throw new errors.IntercomError({
                statusCode: _response.error.statusCode,
                body: _response.error.body,
                rawResponse: _response.rawResponse,
            });
        }

        return handleNonStatusCodeError(
            _response.error,
            _response.rawResponse,
            "POST",
            "/export/cancel/{job_identifier}",
        );
    }

    /**
     * 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.
     *
     * @param {Intercom.DownloadDataExportRequest} request
     * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.dataExport.download({
     *         job_identifier: "job_identifier"
     *     })
     */
    public download(
        request: Intercom.DownloadDataExportRequest,
        requestOptions?: DataExportClient.RequestOptions,
    ): core.HttpResponsePromise<void> {
        return core.HttpResponsePromise.fromPromise(this.__download(request, requestOptions));
    }

    private async __download(
        request: Intercom.DownloadDataExportRequest,
        requestOptions?: DataExportClient.RequestOptions,
    ): Promise<core.WithRawResponse<void>> {
        const { job_identifier: jobIdentifier } = request;
        const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
        const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
            _authRequest.headers,
            this._options?.headers,
            mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }),
            requestOptions?.headers,
        );
        const _response = await (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.IntercomEnvironment.UsProduction,
                `download/content/data/${core.url.encodePathParam(jobIdentifier)}`,
            ),
            method: "GET",
            headers: _headers,
            queryParameters: requestOptions?.queryParams,
            timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000,
            maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
            fetchFn: this._options?.fetch,
            logging: this._options.logging,
        });
        if (_response.ok) {
            return { data: undefined, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            throw new errors.IntercomError({
                statusCode: _response.error.statusCode,
                body: _response.error.body,
                rawResponse: _response.rawResponse,
            });
        }

        return handleNonStatusCodeError(
            _response.error,
            _response.rawResponse,
            "GET",
            "/download/content/data/{job_identifier}",
        );
    }
}
