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

    export interface RequestOptions extends BaseRequestOptions {}
}

export class CustomChannelEventsClient {
    protected readonly _options: NormalizedClientOptionsWithAuth<CustomChannelEventsClient.Options>;

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

    /**
     * Notifies Intercom that a new conversation was created in your custom channel/platform. This triggers conversation creation and workflow automations within Intercom for your custom channel integration.
     * > **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support.
     *
     * @param {Intercom.unstable.CustomChannelBaseEvent} request
     * @param {CustomChannelEventsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.BadRequestError}
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     * @throws {@link Intercom.unstable.UnprocessableEntityError}
     *
     * @example
     *     await client.unstable.customChannelEvents.notifyNewConversation({
     *         event_id: "evt_12345",
     *         external_conversation_id: "conv_67890",
     *         contact: {
     *             type: "user",
     *             external_id: "user_001",
     *             name: "Jane Doe",
     *             email: "jane.doe@example.com"
     *         }
     *     })
     */
    public notifyNewConversation(
        request: Intercom.unstable.CustomChannelBaseEvent,
        requestOptions?: CustomChannelEventsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.CustomChannelNotificationResponse> {
        return core.HttpResponsePromise.fromPromise(this.__notifyNewConversation(request, requestOptions));
    }

    private async __notifyNewConversation(
        request: Intercom.unstable.CustomChannelBaseEvent,
        requestOptions?: CustomChannelEventsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.CustomChannelNotificationResponse>> {
        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,
                "custom_channel_events/notify_new_conversation",
            ),
            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.CustomChannelNotificationResponse,
                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,
                    );
                case 404:
                    throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse);
                case 422:
                    throw new Intercom.unstable.UnprocessableEntityError(
                        _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",
            "/custom_channel_events/notify_new_conversation",
        );
    }

    /**
     * Notifies Intercom that a new message was sent in a conversation on your custom channel/platform. This allows Intercom to process the message and trigger any relevant workflow automations.
     * > **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support.
     *
     * @param {Intercom.unstable.NotifyNewMessageRequest} request
     * @param {CustomChannelEventsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.BadRequestError}
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     * @throws {@link Intercom.unstable.UnprocessableEntityError}
     *
     * @example
     *     await client.unstable.customChannelEvents.notifyNewMessage({
     *         event_id: "evt_54321",
     *         external_conversation_id: "conv_98765",
     *         contact: {
     *             type: "user",
     *             external_id: "user_002",
     *             name: "John Smith",
     *             email: "john.smith@example.com"
     *         },
     *         body: "Hello, I need help with my order."
     *     })
     */
    public notifyNewMessage(
        request: Intercom.unstable.NotifyNewMessageRequest,
        requestOptions?: CustomChannelEventsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.CustomChannelNotificationResponse> {
        return core.HttpResponsePromise.fromPromise(this.__notifyNewMessage(request, requestOptions));
    }

    private async __notifyNewMessage(
        request: Intercom.unstable.NotifyNewMessageRequest,
        requestOptions?: CustomChannelEventsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.CustomChannelNotificationResponse>> {
        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,
                "custom_channel_events/notify_new_message",
            ),
            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.CustomChannelNotificationResponse,
                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,
                    );
                case 404:
                    throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse);
                case 422:
                    throw new Intercom.unstable.UnprocessableEntityError(
                        _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",
            "/custom_channel_events/notify_new_message",
        );
    }

    /**
     * Notifies Intercom that a user selected a quick reply option in your custom channel/platform. This allows Intercom to process the response and trigger any relevant workflow automations.
     * > **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support.
     *
     * @param {Intercom.unstable.NotifyQuickReplySelectedRequest} request
     * @param {CustomChannelEventsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.BadRequestError}
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     * @throws {@link Intercom.unstable.UnprocessableEntityError}
     *
     * @example
     *     await client.unstable.customChannelEvents.notifyQuickReplySelected({
     *         event_id: "evt_67890",
     *         external_conversation_id: "conv_13579",
     *         contact: {
     *             type: "user",
     *             external_id: "user_003",
     *             name: "Alice Example",
     *             email: "alice@example.com"
     *         },
     *         quick_reply_option_id: "1234"
     *     })
     */
    public notifyQuickReplySelected(
        request: Intercom.unstable.NotifyQuickReplySelectedRequest,
        requestOptions?: CustomChannelEventsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.CustomChannelNotificationResponse> {
        return core.HttpResponsePromise.fromPromise(this.__notifyQuickReplySelected(request, requestOptions));
    }

    private async __notifyQuickReplySelected(
        request: Intercom.unstable.NotifyQuickReplySelectedRequest,
        requestOptions?: CustomChannelEventsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.CustomChannelNotificationResponse>> {
        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,
                "custom_channel_events/notify_quick_reply_selected",
            ),
            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.CustomChannelNotificationResponse,
                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,
                    );
                case 404:
                    throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse);
                case 422:
                    throw new Intercom.unstable.UnprocessableEntityError(
                        _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",
            "/custom_channel_events/notify_quick_reply_selected",
        );
    }

    /**
     * Notifies Intercom that a user provided a response to an attribute collector in your custom channel/platform. This allows Intercom to process the attribute and trigger any relevant workflow automations.
     * > **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support.
     *
     * @param {Intercom.unstable.NotifyAttributeCollectedRequest} request
     * @param {CustomChannelEventsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.BadRequestError}
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     * @throws {@link Intercom.unstable.UnprocessableEntityError}
     *
     * @example
     *     await client.unstable.customChannelEvents.notifyAttributeCollected({
     *         event_id: "evt_24680",
     *         external_conversation_id: "conv_11223",
     *         contact: {
     *             type: "user",
     *             external_id: "user_004",
     *             name: "Bob Example",
     *             email: "bob@example.com"
     *         },
     *         attribute: {
     *             id: "shipping_address",
     *             value: "123 Main St, Springfield"
     *         }
     *     })
     */
    public notifyAttributeCollected(
        request: Intercom.unstable.NotifyAttributeCollectedRequest,
        requestOptions?: CustomChannelEventsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.CustomChannelNotificationResponse> {
        return core.HttpResponsePromise.fromPromise(this.__notifyAttributeCollected(request, requestOptions));
    }

    private async __notifyAttributeCollected(
        request: Intercom.unstable.NotifyAttributeCollectedRequest,
        requestOptions?: CustomChannelEventsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.CustomChannelNotificationResponse>> {
        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,
                "custom_channel_events/notify_attribute_collected",
            ),
            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.CustomChannelNotificationResponse,
                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,
                    );
                case 404:
                    throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse);
                case 422:
                    throw new Intercom.unstable.UnprocessableEntityError(
                        _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",
            "/custom_channel_events/notify_attribute_collected",
        );
    }
}
