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

    private async __listCalls(
        request: Intercom.unstable.ListCallsRequest = {},
        requestOptions?: CallsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.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.unstable.CallList, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new Intercom.unstable.UnauthorizedError(
                        _response.error.body as Intercom.unstable.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.unstable.ShowCallRequest} request
     * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.calls.showCall({
     *         id: "id"
     *     })
     */
    public showCall(
        request: Intercom.unstable.ShowCallRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.Call> {
        return core.HttpResponsePromise.fromPromise(this.__showCall(request, requestOptions));
    }

    private async __showCall(
        request: Intercom.unstable.ShowCallRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.Call>> {
        const { id } = 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(id)}`,
            ),
            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.unstable.Call, rawResponse: _response.rawResponse };
        }

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

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

    private async __showCallRecording(
        request: Intercom.unstable.ShowCallRecordingRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): Promise<core.WithRawResponse<void>> {
        const { id } = 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(id)}/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.unstable.UnauthorizedError(
                        _response.error.body as Intercom.unstable.Error_,
                        _response.rawResponse,
                    );
                case 404:
                    throw new Intercom.unstable.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/{id}/recording");
    }

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

    private async __showCallTranscript(
        request: Intercom.unstable.ShowCallTranscriptRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): Promise<core.WithRawResponse<string>> {
        const { id } = 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(id)}/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.unstable.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/{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.unstable.ListCallsWithTranscriptsRequest} request
     * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.BadRequestError}
     * @throws {@link Intercom.unstable.UnauthorizedError}
     *
     * @example
     *     await client.unstable.calls.listCallsWithTranscripts({
     *         conversation_ids: ["64619700005694", "64619700005695"]
     *     })
     */
    public listCallsWithTranscripts(
        request: Intercom.unstable.ListCallsWithTranscriptsRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.ListCallsWithTranscriptsResponse> {
        return core.HttpResponsePromise.fromPromise(this.__listCallsWithTranscripts(request, requestOptions));
    }

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

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

    /**
     * Register a Fin Voice call with Intercom. This endpoint creates an external reference
     * that links an external call identifier to an Intercom call and conversation.
     *
     * The call can be from different sources:
     * - AWS Connect (default)
     * - Five9
     * - Zoom Phone
     *
     * @param {Intercom.unstable.RegisterFinVoiceCallRequest} request
     * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.BadRequestError}
     * @throws {@link Intercom.unstable.ConflictError}
     *
     * @example
     *     await client.unstable.calls.registerFinVoiceCall({
     *         phone_number: "+1234567890",
     *         call_id: "call-123-abc"
     *     })
     */
    public registerFinVoiceCall(
        request?: Intercom.unstable.RegisterFinVoiceCallRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.AiCallResponse> {
        return core.HttpResponsePromise.fromPromise(this.__registerFinVoiceCall(request, requestOptions));
    }

    private async __registerFinVoiceCall(
        request?: Intercom.unstable.RegisterFinVoiceCallRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.AiCallResponse>> {
        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,
                "fin_voice/register",
            ),
            method: "POST",
            headers: _headers,
            contentType: "application/json",
            queryParameters: requestOptions?.queryParams,
            requestType: "json",
            body: request != null ? request : undefined,
            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.unstable.AiCallResponse, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 400:
                    throw new Intercom.unstable.BadRequestError(_response.error.body as unknown, _response.rawResponse);
                case 409:
                    throw new Intercom.unstable.ConflictError(
                        _response.error.body as Intercom.unstable.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", "/fin_voice/register");
    }

    /**
     * Retrieve information about a Fin Voice call using the external reference ID.
     *
     * @param {Intercom.unstable.CollectFinVoiceCallByIdRequest} request
     * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.calls.collectFinVoiceCallById({
     *         id: 1
     *     })
     */
    public collectFinVoiceCallById(
        request: Intercom.unstable.CollectFinVoiceCallByIdRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.AiCallResponse> {
        return core.HttpResponsePromise.fromPromise(this.__collectFinVoiceCallById(request, requestOptions));
    }

    private async __collectFinVoiceCallById(
        request: Intercom.unstable.CollectFinVoiceCallByIdRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.AiCallResponse>> {
        const { id } = 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,
                `fin_voice/collect/${core.url.encodePathParam(id)}`,
            ),
            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.unstable.AiCallResponse, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 404:
                    throw new Intercom.unstable.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", "/fin_voice/collect/{id}");
    }

    /**
     * Retrieve information about a Fin Voice call using the external call identifier.
     *
     * @param {Intercom.unstable.CollectFinVoiceCallByExternalIdRequest} request
     * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.calls.collectFinVoiceCallByExternalId({
     *         external_id: "external_id"
     *     })
     */
    public collectFinVoiceCallByExternalId(
        request: Intercom.unstable.CollectFinVoiceCallByExternalIdRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.AiCallResponse> {
        return core.HttpResponsePromise.fromPromise(this.__collectFinVoiceCallByExternalId(request, requestOptions));
    }

    private async __collectFinVoiceCallByExternalId(
        request: Intercom.unstable.CollectFinVoiceCallByExternalIdRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.AiCallResponse>> {
        const { external_id: externalId } = 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,
                `fin_voice/external_id/${core.url.encodePathParam(externalId)}`,
            ),
            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.unstable.AiCallResponse, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 404:
                    throw new Intercom.unstable.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",
            "/fin_voice/external_id/{external_id}",
        );
    }

    /**
     * Retrieve information about a Fin Voice call using the phone number.
     *
     * Returns the most recent matched call for the given phone number, ordered by creation date.
     *
     * @param {Intercom.unstable.CollectFinVoiceCallByPhoneNumberRequest} request
     * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.calls.collectFinVoiceCallByPhoneNumber({
     *         phone_number: "phone_number"
     *     })
     */
    public collectFinVoiceCallByPhoneNumber(
        request: Intercom.unstable.CollectFinVoiceCallByPhoneNumberRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.Error_> {
        return core.HttpResponsePromise.fromPromise(this.__collectFinVoiceCallByPhoneNumber(request, requestOptions));
    }

    private async __collectFinVoiceCallByPhoneNumber(
        request: Intercom.unstable.CollectFinVoiceCallByPhoneNumberRequest,
        requestOptions?: CallsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.Error_>> {
        const { phone_number: phoneNumber } = 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,
                `fin_voice/phone_number/${core.url.encodePathParam(phoneNumber)}`,
            ),
            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.unstable.Error_, rawResponse: _response.rawResponse };
        }

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