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

    export interface RequestOptions extends BaseRequestOptions {}
}

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

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

    /**
     * You can fetch a list of companies that are associated to a contact.
     *
     * @param {Intercom.ListAttachedCompaniesRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.contacts.listAttachedCompanies({
     *         contact_id: "63a07ddf05a32042dffac965",
     *         page: 1,
     *         per_page: 1
     *     })
     */
    public async listAttachedCompanies(
        request: Intercom.ListAttachedCompaniesRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.Page<Intercom.Company, Intercom.ContactAttachedCompanies>> {
        const list = core.HttpResponsePromise.interceptFunction(
            async (
                request: Intercom.ListAttachedCompaniesRequest,
            ): Promise<core.WithRawResponse<Intercom.ContactAttachedCompanies>> => {
                const { contact_id: contactId, 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,
                        `contacts/${core.url.encodePathParam(contactId)}/companies`,
                    ),
                    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.ContactAttachedCompanies,
                        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",
                    "/contacts/{contact_id}/companies",
                );
            },
        );
        let _offset = request?.page != null ? request?.page : 1;
        const dataWithRawResponse = await list(request).withRawResponse();
        return new core.Page<Intercom.Company, Intercom.ContactAttachedCompanies>({
            response: dataWithRawResponse.data,
            rawResponse: dataWithRawResponse.rawResponse,
            hasNextPage: (response) => (response?.companies ?? []).length > 0,
            getItems: (response) => response?.companies ?? [],
            loadPage: (_response) => {
                _offset += 1;
                return list(core.setObjectProperty(request, "page", _offset));
            },
        });
    }

    /**
     * You can fetch a list of segments that are associated to a contact.
     *
     * @param {Intercom.ListSegmentsAttachedToContactRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.contacts.listAttachedSegments({
     *         contact_id: "63a07ddf05a32042dffac965"
     *     })
     */
    public listAttachedSegments(
        request: Intercom.ListSegmentsAttachedToContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.ContactSegments> {
        return core.HttpResponsePromise.fromPromise(this.__listAttachedSegments(request, requestOptions));
    }

    private async __listAttachedSegments(
        request: Intercom.ListSegmentsAttachedToContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.ContactSegments>> {
        const { contact_id: contactId } = 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,
                `contacts/${core.url.encodePathParam(contactId)}/segments`,
            ),
            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.ContactSegments, 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",
            "/contacts/{contact_id}/segments",
        );
    }

    /**
     * You can fetch a list of subscription types that are attached to a contact. These can be subscriptions that a user has 'opted-in' to or has 'opted-out' from, depending on the subscription type.
     * This will return a list of Subscription Type objects that the contact is associated with.
     *
     * The data property will show a combined list of:
     *
     *   1.Opt-out subscription types that the user has opted-out from.
     *   2.Opt-in subscription types that the user has opted-in to receiving.
     *
     * @param {Intercom.ListAttachedSubscriptionsRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.contacts.listAttachedSubscriptions({
     *         contact_id: "63a07ddf05a32042dffac965"
     *     })
     */
    public listAttachedSubscriptions(
        request: Intercom.ListAttachedSubscriptionsRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.SubscriptionTypeList> {
        return core.HttpResponsePromise.fromPromise(this.__listAttachedSubscriptions(request, requestOptions));
    }

    private async __listAttachedSubscriptions(
        request: Intercom.ListAttachedSubscriptionsRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.SubscriptionTypeList>> {
        const { contact_id: contactId } = 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,
                `contacts/${core.url.encodePathParam(contactId)}/subscriptions`,
            ),
            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.SubscriptionTypeList, 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",
            "/contacts/{contact_id}/subscriptions",
        );
    }

    /**
     * You can add a specific subscription to a contact. In Intercom, we have two different subscription types based on user consent - opt-out and opt-in:
     *
     *   1.Attaching a contact to an opt-out subscription type will opt that user out from receiving messages related to that subscription type.
     *
     *   2.Attaching a contact to an opt-in subscription type will opt that user in to receiving messages related to that subscription type.
     *
     * This will return a subscription type model for the subscription type that was added to the contact.
     *
     * @param {Intercom.AttachSubscriptionToContactRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.contacts.attachSubscription({
     *         contact_id: "63a07ddf05a32042dffac965",
     *         id: "37846",
     *         consent_type: "opt_in"
     *     })
     *
     * @example
     *     await client.contacts.attachSubscription({
     *         contact_id: "63a07ddf05a32042dffac965",
     *         id: "invalid_id",
     *         consent_type: "opt_in"
     *     })
     */
    public attachSubscription(
        request: Intercom.AttachSubscriptionToContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.SubscriptionType> {
        return core.HttpResponsePromise.fromPromise(this.__attachSubscription(request, requestOptions));
    }

    private async __attachSubscription(
        request: Intercom.AttachSubscriptionToContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.SubscriptionType>> {
        const { contact_id: contactId, ..._body } = 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,
                `contacts/${core.url.encodePathParam(contactId)}/subscriptions`,
            ),
            method: "POST",
            headers: _headers,
            contentType: "application/json",
            queryParameters: requestOptions?.queryParams,
            requestType: "json",
            body: _body,
            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.SubscriptionType, 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,
            "POST",
            "/contacts/{contact_id}/subscriptions",
        );
    }

    /**
     * You can remove a specific subscription from a contact. This will return a subscription type model for the subscription type that was removed from the contact.
     *
     * @param {Intercom.DetachSubscriptionFromContactRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.contacts.detachSubscription({
     *         contact_id: "63a07ddf05a32042dffac965",
     *         subscription_id: "37846"
     *     })
     */
    public detachSubscription(
        request: Intercom.DetachSubscriptionFromContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.SubscriptionType> {
        return core.HttpResponsePromise.fromPromise(this.__detachSubscription(request, requestOptions));
    }

    private async __detachSubscription(
        request: Intercom.DetachSubscriptionFromContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.SubscriptionType>> {
        const { contact_id: contactId, subscription_id: subscriptionId } = 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,
                `contacts/${core.url.encodePathParam(contactId)}/subscriptions/${core.url.encodePathParam(subscriptionId)}`,
            ),
            method: "DELETE",
            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.SubscriptionType, 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,
            "DELETE",
            "/contacts/{contact_id}/subscriptions/{subscription_id}",
        );
    }

    /**
     * You can fetch a list of all tags that are attached to a specific contact.
     *
     * @param {Intercom.ListTagsAttachedToContactRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.contacts.listAttachedTags({
     *         contact_id: "63a07ddf05a32042dffac965"
     *     })
     */
    public listAttachedTags(
        request: Intercom.ListTagsAttachedToContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.TagList> {
        return core.HttpResponsePromise.fromPromise(this.__listAttachedTags(request, requestOptions));
    }

    private async __listAttachedTags(
        request: Intercom.ListTagsAttachedToContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.TagList>> {
        const { contact_id: contactId } = 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,
                `contacts/${core.url.encodePathParam(contactId)}/tags`,
            ),
            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.TagList, 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", "/contacts/{contact_id}/tags");
    }

    /**
     * You can fetch the details of a single contact.
     *
     * @param {Intercom.FindContactRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.contacts.find({
     *         contact_id: "63a07ddf05a32042dffac965"
     *     })
     */
    public find(
        request: Intercom.FindContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.ContactsFindResponse> {
        return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions));
    }

    private async __find(
        request: Intercom.FindContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.ContactsFindResponse>> {
        const { contact_id: contactId } = 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,
                `contacts/${core.url.encodePathParam(contactId)}`,
            ),
            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.ContactsFindResponse, 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", "/contacts/{contact_id}");
    }

    /**
     * You can update an existing contact (ie. user or lead).
     *
     * {% admonition type="info" %}
     *   This endpoint handles both **contact updates** and **custom object associations**.
     *
     *   See _`update a contact with an association to a custom object instance`_ in the request/response examples to see the custom object association format.
     * {% /admonition %}
     *
     * @param {Intercom.UpdateContactRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.contacts.update({
     *         contact_id: "63a07ddf05a32042dffac965",
     *         email: "joebloggs@intercom.io",
     *         name: "joe bloggs"
     *     })
     *
     * @example
     *     await client.contacts.update({
     *         contact_id: "63a07ddf05a32042dffac965",
     *         custom_attributes: {
     *             "order": [
     *                 "21"
     *             ]
     *         }
     *     })
     */
    public update(
        request: Intercom.UpdateContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.ContactsUpdateResponse> {
        return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions));
    }

    private async __update(
        request: Intercom.UpdateContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.ContactsUpdateResponse>> {
        const { contact_id: contactId, ..._body } = 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,
                `contacts/${core.url.encodePathParam(contactId)}`,
            ),
            method: "PUT",
            headers: _headers,
            contentType: "application/json",
            queryParameters: requestOptions?.queryParams,
            requestType: "json",
            body: _body,
            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.ContactsUpdateResponse, 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, "PUT", "/contacts/{contact_id}");
    }

    /**
     * You can delete a single contact.
     *
     * @param {Intercom.DeleteContactRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.contacts.delete({
     *         contact_id: "contact_id"
     *     })
     */
    public delete(
        request: Intercom.DeleteContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.ContactDeleted> {
        return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions));
    }

    private async __delete(
        request: Intercom.DeleteContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.ContactDeleted>> {
        const { contact_id: contactId } = 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,
                `contacts/${core.url.encodePathParam(contactId)}`,
            ),
            method: "DELETE",
            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.ContactDeleted, 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, "DELETE", "/contacts/{contact_id}");
    }

    /**
     * You can merge a contact with a `role` of `lead` into a contact with a `role` of `user`.
     *
     * @param {Intercom.MergeContactsRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.contacts.mergeLeadInUser({
     *         from: "6762f0d51bb69f9f2193bb7f",
     *         into: "6762f0d51bb69f9f2193bb80"
     *     })
     */
    public mergeLeadInUser(
        request: Intercom.MergeContactsRequest = {},
        requestOptions?: ContactsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.ContactsMergeLeadInUserResponse> {
        return core.HttpResponsePromise.fromPromise(this.__mergeLeadInUser(request, requestOptions));
    }

    private async __mergeLeadInUser(
        request: Intercom.MergeContactsRequest = {},
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.ContactsMergeLeadInUserResponse>> {
        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,
                "contacts/merge",
            ),
            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.ContactsMergeLeadInUserResponse,
                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, "POST", "/contacts/merge");
    }

    /**
     * You can search for multiple contacts by the value of their attributes in order to fetch exactly who you want.
     *
     * To search for contacts, you need to send a `POST` request to `https://api.intercom.io/contacts/search`.
     *
     * This will accept a query object in the body which will define your filters in order to search for contacts.
     *
     * {% admonition type="warning" name="Optimizing search queries" %}
     *   Search queries can be complex, so optimizing them can help the performance of your search.
     *   Use the `AND` and `OR` operators to combine multiple filters to get the exact results you need and utilize
     *   pagination to limit the number of results returned. The default is `50` results per page.
     *   See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request) for more details on how to use the `starting_after` param.
     * {% /admonition %}
     * ### Contact Creation Delay
     *
     * If a contact has recently been created, there is a possibility that it will not yet be available when searching. This means that it may not appear in the response. This delay can take a few minutes. If you need to be instantly notified it is recommended to use webhooks and iterate to see if they match your search filters.
     *
     * ### Nesting & Limitations
     *
     * You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4).
     * There are some limitations to the amount of multiple's there can be:
     * * There's a limit of max 2 nested filters
     * * There's a limit of max 15 filters for each AND or OR group
     *
     * ### Searching for Timestamp Fields
     *
     * All timestamp fields (created_at, updated_at etc.) are indexed as Dates for Contact Search queries; Datetime queries are not currently supported. This means you can only query for timestamp fields by day - not hour, minute or second.
     * For example, if you search for all Contacts with a created_at value greater (>) than 1577869200 (the UNIX timestamp for January 1st, 2020 9:00 AM), that will be interpreted as 1577836800 (January 1st, 2020 12:00 AM). The search results will then include Contacts created from January 2nd, 2020 12:00 AM onwards.
     * If you'd like to get contacts created on January 1st, 2020 you should search with a created_at value equal (=) to 1577836800 (January 1st, 2020 12:00 AM).
     * This behaviour applies only to timestamps used in search queries. The search results will still contain the full UNIX timestamp and be sorted accordingly.
     *
     * ### Accepted Fields
     *
     * Most key listed as part of the Contacts Model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foorbar"`).
     *
     * | Field                              | Type                           |
     * | ---------------------------------- | ------------------------------ |
     * | id                                 | String                         |
     * | role                               | String<br>Accepts user or lead |
     * | name                               | String                         |
     * | avatar                             | String                         |
     * | owner_id                           | Integer                        |
     * | email                              | String                         |
     * | email_domain                       | String                         |
     * | phone                              | String                         |
     * | external_id                        | String                         |
     * | created_at                         | Date (UNIX Timestamp)          |
     * | signed_up_at                       | Date (UNIX Timestamp)          |
     * | updated_at                         | Date (UNIX Timestamp)          |
     * | last_seen_at                       | Date (UNIX Timestamp)          |
     * | last_contacted_at                  | Date (UNIX Timestamp)          |
     * | last_replied_at                    | Date (UNIX Timestamp)          |
     * | last_email_opened_at               | Date (UNIX Timestamp)          |
     * | last_email_clicked_at              | Date (UNIX Timestamp)          |
     * | language_override                  | String                         |
     * | browser                            | String                         |
     * | browser_language                   | String                         |
     * | os                                 | String                         |
     * | location.country                   | String                         |
     * | location.region                    | String                         |
     * | location.city                      | String                         |
     * | unsubscribed_from_emails           | Boolean                        |
     * | marked_email_as_spam               | Boolean                        |
     * | has_hard_bounced                   | Boolean                        |
     * | ios_last_seen_at                   | Date (UNIX Timestamp)          |
     * | ios_app_version                    | String                         |
     * | ios_device                         | String                         |
     * | ios_app_device                     | String                         |
     * | ios_os_version                     | String                         |
     * | ios_app_name                       | String                         |
     * | ios_sdk_version                    | String                         |
     * | android_last_seen_at               | Date (UNIX Timestamp)          |
     * | android_app_version                | String                         |
     * | android_device                     | String                         |
     * | android_app_name                   | String                         |
     * | andoid_sdk_version                 | String                         |
     * | segment_id                         | String                         |
     * | tag_id                             | String                         |
     * | custom_attributes.{attribute_name} | String                         |
     *
     * ### Accepted Operators
     *
     * {% admonition type="warning" name="Searching based on `created_at`" %}
     *   You cannot use the `<=` or `>=` operators to search by `created_at`.
     * {% /admonition %}
     *
     * The table below shows the operators you can use to define how you want to search for the value.  The operator should be put in as a string (`"="`). The operator has to be compatible with the field's type (eg. you cannot search with `>` for a given string value as it's only compatible for integer's and dates).
     *
     * | Operator | Valid Types                      | Description                                                      |
     * | :------- | :------------------------------- | :--------------------------------------------------------------- |
     * | =        | All                              | Equals                                                           |
     * | !=       | All                              | Doesn't Equal                                                    |
     * | IN       | All                              | In<br>Shortcut for `OR` queries<br>Values must be in Array       |
     * | NIN      | All                              | Not In<br>Shortcut for `OR !` queries<br>Values must be in Array |
     * | >        | Integer<br>Date (UNIX Timestamp) | Greater than                                                     |
     * | <       | Integer<br>Date (UNIX Timestamp) | Lower than                                                       |
     * | ~        | String                           | Contains                                                         |
     * | !~       | String                           | Doesn't Contain                                                  |
     * | ^        | String                           | Starts With                                                      |
     * | $        | String                           | Ends With                                                        |
     *
     * @param {Intercom.SearchRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.contacts.search({
     *         query: {
     *             operator: "AND",
     *             value: [{
     *                     field: "created_at",
     *                     operator: ">",
     *                     value: "1306054154"
     *                 }]
     *         },
     *         pagination: {
     *             per_page: 5
     *         }
     *     })
     */
    public async search(
        request: Intercom.SearchRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.Page<Intercom.Contact, Intercom.ContactList>> {
        const list = core.HttpResponsePromise.interceptFunction(
            async (request: Intercom.SearchRequest): Promise<core.WithRawResponse<Intercom.ContactList>> => {
                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,
                        "contacts/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.ContactList, 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, "POST", "/contacts/search");
            },
        );
        const dataWithRawResponse = await list(request).withRawResponse();
        return new core.Page<Intercom.Contact, Intercom.ContactList>({
            response: dataWithRawResponse.data,
            rawResponse: dataWithRawResponse.rawResponse,
            hasNextPage: (response) =>
                response?.pages?.next?.starting_after != null &&
                !(
                    typeof response?.pages?.next?.starting_after === "string" &&
                    response?.pages?.next?.starting_after === ""
                ),
            getItems: (response) => response?.data ?? [],
            loadPage: (response) => {
                return list(
                    core.setObjectProperty(request, "pagination.starting_after", response?.pages?.next?.starting_after),
                );
            },
        });
    }

    /**
     * You can fetch a list of all contacts (ie. users or leads) in your workspace.
     * {% admonition type="warning" name="Pagination" %}
     *   You can use pagination to limit the number of results returned. The default is `50` results per page.
     *   See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param.
     * {% /admonition %}
     *
     * @param {Intercom.ListContactsRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.contacts.list()
     */
    public async list(
        request: Intercom.ListContactsRequest = {},
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.Page<Intercom.Contact, Intercom.ContactList>> {
        const list = core.HttpResponsePromise.interceptFunction(
            async (request: Intercom.ListContactsRequest): Promise<core.WithRawResponse<Intercom.ContactList>> => {
                const { page, per_page: perPage, starting_after: startingAfter } = 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();
                }
                if (startingAfter != null) {
                    _queryParams.starting_after = startingAfter;
                }
                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,
                        "contacts",
                    ),
                    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.ContactList, 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", "/contacts");
            },
        );
        const dataWithRawResponse = await list(request).withRawResponse();
        return new core.Page<Intercom.Contact, Intercom.ContactList>({
            response: dataWithRawResponse.data,
            rawResponse: dataWithRawResponse.rawResponse,
            hasNextPage: (response) =>
                response?.pages?.next?.starting_after != null &&
                !(
                    typeof response?.pages?.next?.starting_after === "string" &&
                    response?.pages?.next?.starting_after === ""
                ),
            getItems: (response) => response?.data ?? [],
            loadPage: (response) => {
                return list(core.setObjectProperty(request, "starting_after", response?.pages?.next?.starting_after));
            },
        });
    }

    /**
     * You can create a new contact (ie. user or lead).
     *
     * @param {Intercom.CreateContactRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.contacts.create({
     *         email: "joebloggs@intercom.io"
     *     })
     */
    public create(
        request: Intercom.CreateContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.ContactsCreateResponse> {
        return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));
    }

    private async __create(
        request: Intercom.CreateContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.ContactsCreateResponse>> {
        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,
                "contacts",
            ),
            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.ContactsCreateResponse, 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, "POST", "/contacts");
    }

    /**
     * You can fetch the details of a single contact by external ID. Note that this endpoint only supports users and not leads.
     *
     * @param {Intercom.ShowContactByExternalIdRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.contacts.showContactByExternalId({
     *         external_id: "cdd29344-5e0c-4ef0-ac56-f9ba2979bc27"
     *     })
     */
    public showContactByExternalId(
        request: Intercom.ShowContactByExternalIdRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.ShowContactByExternalIdResponse> {
        return core.HttpResponsePromise.fromPromise(this.__showContactByExternalId(request, requestOptions));
    }

    private async __showContactByExternalId(
        request: Intercom.ShowContactByExternalIdRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.ShowContactByExternalIdResponse>> {
        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,
                `contacts/find_by_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.ShowContactByExternalIdResponse,
                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",
            "/contacts/find_by_external_id/{external_id}",
        );
    }

    /**
     * You can archive a single contact.
     *
     * @param {Intercom.ArchiveContactRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.contacts.archive({
     *         contact_id: "63a07ddf05a32042dffac965"
     *     })
     */
    public archive(
        request: Intercom.ArchiveContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.ContactArchived> {
        return core.HttpResponsePromise.fromPromise(this.__archive(request, requestOptions));
    }

    private async __archive(
        request: Intercom.ArchiveContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.ContactArchived>> {
        const { contact_id: contactId } = 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,
                `contacts/${core.url.encodePathParam(contactId)}/archive`,
            ),
            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.ContactArchived, 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",
            "/contacts/{contact_id}/archive",
        );
    }

    /**
     * You can unarchive a single contact.
     *
     * @param {Intercom.UnarchiveContactRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.contacts.unarchive({
     *         contact_id: "63a07ddf05a32042dffac965"
     *     })
     */
    public unarchive(
        request: Intercom.UnarchiveContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.ContactUnarchived> {
        return core.HttpResponsePromise.fromPromise(this.__unarchive(request, requestOptions));
    }

    private async __unarchive(
        request: Intercom.UnarchiveContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.ContactUnarchived>> {
        const { contact_id: contactId } = 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,
                `contacts/${core.url.encodePathParam(contactId)}/unarchive`,
            ),
            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.ContactUnarchived, 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",
            "/contacts/{contact_id}/unarchive",
        );
    }

    /**
     * Block a single contact.<br>**Note:** conversations of the contact will also be archived during the process.<br>More details in [FAQ How do I block Inbox spam?](https://www.intercom.com/help/en/articles/8838656-inbox-faqs)
     *
     * @param {Intercom.BlockContactRequest} request
     * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.contacts.blockContact({
     *         contact_id: "63a07ddf05a32042dffac965"
     *     })
     */
    public blockContact(
        request: Intercom.BlockContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.ContactBlocked> {
        return core.HttpResponsePromise.fromPromise(this.__blockContact(request, requestOptions));
    }

    private async __blockContact(
        request: Intercom.BlockContactRequest,
        requestOptions?: ContactsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.ContactBlocked>> {
        const { contact_id: contactId } = 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,
                `contacts/${core.url.encodePathParam(contactId)}/block`,
            ),
            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.ContactBlocked, 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", "/contacts/{contact_id}/block");
    }
}
