// 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 CallsClient {
    export interface Options extends BaseClientOptions {}

    export interface RequestOptions extends BaseRequestOptions {}
}

/**
 * Everything about your Calls
 */
export class CallsClient {
    protected readonly _options: NormalizedClientOptionsWithAuth<CallsClient.Options>;

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

    /**
     * Retrieve a paginated list of calls.
     *
     * @param {Intercom.ListCallsRequest} request
     * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.calls.listCalls({
     *         page: 1,
     *         per_page: 1
     *     })
     */
    public listCalls(
        request: Intercom.ListCallsRequest = {},
        requestOptions?: CallsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.CallList> {
        return core.HttpResponsePromise.fromPromise(this.__listCalls(request, requestOptions));
    }

    private async __listCalls(
        request: Intercom.ListCallsRequest = {},
        requestOptions?: CallsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.CallList>> {
        const { page, per_page: perPage } = request;
        const _queryParams: Record<string, string | string[] | object | object[] | null> = {};
        if (page != null) {
            _queryParams.page = page.toString();
        }

        if (perPage != null) {
            _queryParams.per_page = perPage.toString();
        }

        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,
                "calls",
            ),
            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.CallList, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new Intercom.UnauthorizedError(
                        _response.error.body as Intercom.Error_,
                        _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", "/calls");
    }

    /**
     * Retrieve a single call by id.
     *
     * @param {Intercom.ShowCallRequest} request
     * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.calls.showCall({
     *         call_id: "call_id"
     *     })
     */
    public showCall(
        request: Intercom.ShowCallRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.Call> {
        return core.HttpResponsePromise.fromPromise(this.__showCall(request, requestOptions));
    }

    private async __showCall(
        request: Intercom.ShowCallRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.Call>> {
        const { call_id: callId } = 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,
                `calls/${core.url.encodePathParam(callId)}`,
            ),
            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.Call, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new Intercom.UnauthorizedError(
                        _response.error.body as Intercom.Error_,
                        _response.rawResponse,
                    );
                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", "/calls/{call_id}");
    }

    /**
     * Redirects to a signed URL for the call's recording if it exists.
     *
     * @param {Intercom.ShowCallRecordingRequest} request
     * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.calls.showCallRecording({
     *         call_id: "call_id"
     *     })
     */
    public showCallRecording(
        request: Intercom.ShowCallRecordingRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): core.HttpResponsePromise<void> {
        return core.HttpResponsePromise.fromPromise(this.__showCallRecording(request, requestOptions));
    }

    private async __showCallRecording(
        request: Intercom.ShowCallRecordingRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): Promise<core.WithRawResponse<void>> {
        const { call_id: callId } = 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,
                `calls/${core.url.encodePathParam(callId)}/recording`,
            ),
            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") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new Intercom.UnauthorizedError(
                        _response.error.body as Intercom.Error_,
                        _response.rawResponse,
                    );
                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", "/calls/{call_id}/recording");
    }

    /**
     * Returns the transcript for the specified call as a downloadable text file.
     *
     * @param {Intercom.ShowCallTranscriptRequest} request
     * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.calls.showCallTranscript({
     *         call_id: "call_id"
     *     })
     */
    public showCallTranscript(
        request: Intercom.ShowCallTranscriptRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): core.HttpResponsePromise<string> {
        return core.HttpResponsePromise.fromPromise(this.__showCallTranscript(request, requestOptions));
    }

    private async __showCallTranscript(
        request: Intercom.ShowCallTranscriptRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): Promise<core.WithRawResponse<string>> {
        const { call_id: callId } = 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,
                `calls/${core.url.encodePathParam(callId)}/transcript`,
            ),
            method: "GET",
            headers: _headers,
            queryParameters: requestOptions?.queryParams,
            responseType: "text",
            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 string, 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", "/calls/{call_id}/transcript");
    }

    /**
     * Retrieve calls by a list of conversation ids and include transcripts when available.
     * A maximum of 20 `conversation_ids` can be provided. If none are provided or more than 20 are provided, a 400 error is returned.
     *
     * @param {Intercom.ListCallsWithTranscriptsRequest} request
     * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.BadRequestError}
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.calls.listCallsWithTranscripts({
     *         conversation_ids: ["64619700005694", "64619700005695"]
     *     })
     */
    public listCallsWithTranscripts(
        request: Intercom.ListCallsWithTranscriptsRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.ListCallsWithTranscriptsResponse> {
        return core.HttpResponsePromise.fromPromise(this.__listCallsWithTranscripts(request, requestOptions));
    }

    private async __listCallsWithTranscripts(
        request: Intercom.ListCallsWithTranscriptsRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.ListCallsWithTranscriptsResponse>> {
        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,
                "calls/search",
            ),
            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.ListCallsWithTranscriptsResponse,
                rawResponse: _response.rawResponse,
            };
        }

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

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/calls/search");
    }
}
