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

    export interface RequestOptions extends BaseRequestOptions {}
}

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

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

    /**
     * You can create a message that has been initiated by an admin. The conversation can be either an in-app message, an email, sms or whatsapp.
     *
     * > 🚧 Sending for visitors
     * >
     * > There can be a short delay between when a contact is created and when a contact becomes available to be messaged through the API. A 404 Not Found error will be returned in this case.
     *
     * This will return the Message model that has been created.
     *
     * > 🚧 Retrieving Associated Conversations
     * >
     * > As this is a message, there will be no conversation present until the contact responds. Once they do, you will have to search for a contact's conversations with the id of the message.
     *
     * @param {Intercom.unstable.CreateMessageRequest | undefined} request
     * @param {MessagesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.BadRequestError}
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.ForbiddenError}
     * @throws {@link Intercom.unstable.UnprocessableEntityError}
     *
     * @example
     *     await client.unstable.messages.createMessage({
     *         "from": {
     *             "type": "user",
     *             "id": "6762f2341bb69f9f2193bc17"
     *         },
     *         "body": "heyy",
     *         "referer": "https://twitter.com/bob"
     *     })
     *
     * @example
     *     await client.unstable.messages.createMessage({
     *         "from": {
     *             "type": "lead",
     *             "id": "6762f2371bb69f9f2193bc18"
     *         },
     *         "body": "heyy",
     *         "referer": "https://twitter.com/bob"
     *     })
     *
     * @example
     *     await client.unstable.messages.createMessage({
     *         "from": {
     *             "type": "admin",
     *             "id": "991267816"
     *         },
     *         "to": [
     *             {
     *                 "type": "user",
     *                 "id": "6762f2391bb69f9f2193bc19"
     *             },
     *             {
     *                 "type": "lead",
     *                 "id": "6762f23c1bb69f9f2193bc1b"
     *             },
     *             {
     *                 "type": "user",
     *                 "id": "6762f23d1bb69f9f2193bc1c"
     *             }
     *         ],
     *         "cc": [
     *             {
     *                 "type": "user",
     *                 "id": "6762f23e1bb69f9f2193bc1d"
     *             },
     *             {
     *                 "type": "user",
     *                 "id": "6762f23f1bb69f9f2193bc1e"
     *             }
     *         ],
     *         "bcc": [
     *             {
     *                 "type": "user",
     *                 "id": "6762f23e1bb69f9f2193bc2f"
     *             }
     *         ],
     *         "message_type": "conversation",
     *         "body": "heyy"
     *     })
     *
     * @example
     *     await client.unstable.messages.createMessage({
     *         "from": {
     *             "type": "admin",
     *             "id": "991267817"
     *         },
     *         "to": {
     *             "type": "user",
     *             "id": "6762f23a1bb69f9f2193bc1a"
     *         },
     *         "message_type": "sms",
     *         "body": "heyy"
     *     })
     *
     * @example
     *     await client.unstable.messages.createMessage({
     *         "from": {
     *             "type": "admin",
     *             "id": "991267817"
     *         },
     *         "to": {
     *             "phone": 5547999998888,
     *             "name": "John Doe"
     *         },
     *         "message_type": "whatsapp",
     *         "components": [
     *             {
     *                 "type": "BODY",
     *                 "parameters": [
     *                     {
     *                         "type": "text",
     *                         "text": "Username 123"
     *                     }
     *                 ]
     *             }
     *         ],
     *         "template": "keep_live",
     *         "locale": "en"
     *     })
     *
     * @example
     *     await client.unstable.messages.createMessage({
     *         "from": {
     *             "type": "admin",
     *             "id": "991267818"
     *         },
     *         "to": {
     *             "type": "user",
     *             "id": "6762f23b1bb69f9f2193bc1a"
     *         },
     *         "message_type": "inapp",
     *         "subject": "heyy"
     *     })
     *
     * @example
     *     await client.unstable.messages.createMessage({
     *         "from": {
     *             "type": "admin",
     *             "id": "991267819"
     *         },
     *         "to": {
     *             "type": "user",
     *             "user_id": "70"
     *         },
     *         "message_type": "email",
     *         "body": "hey there"
     *     })
     *
     * @example
     *     await client.unstable.messages.createMessage({
     *         "from": {
     *             "type": "admin",
     *             "id": "991267820"
     *         },
     *         "to": {
     *             "type": "user",
     *             "id": "6762f23d1bb69f9f2193bc1c"
     *         },
     *         "message_type": "email",
     *         "subject": "heyy"
     *     })
     *
     * @example
     *     await client.unstable.messages.createMessage({
     *         "from": {
     *             "type": "admin",
     *             "id": "991267821"
     *         },
     *         "to": {
     *             "type": "user",
     *             "id": "6762f23b1bb69f9f2193bc1d"
     *         },
     *         "message_type": "sms",
     *         "body": "heyy https://picsum.photos/200/300"
     *     })
     */
    public createMessage(
        request?: Intercom.unstable.CreateMessageRequest | undefined,
        requestOptions?: MessagesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.Message> {
        return core.HttpResponsePromise.fromPromise(this.__createMessage(request, requestOptions));
    }

    private async __createMessage(
        request?: Intercom.unstable.CreateMessageRequest | undefined,
        requestOptions?: MessagesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.Message>> {
        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,
                "messages",
            ),
            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.Message, 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 403:
                    throw new Intercom.unstable.ForbiddenError(
                        _response.error.body as Intercom.unstable.Error_,
                        _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", "/messages");
    }

    /**
     * Retrieves statuses of messages sent from the Outbound module. Currently, this API only supports WhatsApp messages.
     *
     *
     * This endpoint returns paginated status events for WhatsApp messages sent via the Outbound module, providing
     * information about delivery state and related message details.
     *
     * @param {Intercom.unstable.GetWhatsAppMessageStatusRequest} request
     * @param {MessagesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.BadRequestError}
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.ForbiddenError}
     * @throws {@link Intercom.unstable.InternalServerError}
     *
     * @example
     *     await client.unstable.messages.getWhatsAppMessageStatus({
     *         ruleset_id: "ruleset_id",
     *         per_page: 1,
     *         starting_after: "starting_after"
     *     })
     */
    public getWhatsAppMessageStatus(
        request: Intercom.unstable.GetWhatsAppMessageStatusRequest,
        requestOptions?: MessagesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.WhatsappMessageStatusList> {
        return core.HttpResponsePromise.fromPromise(this.__getWhatsAppMessageStatus(request, requestOptions));
    }

    private async __getWhatsAppMessageStatus(
        request: Intercom.unstable.GetWhatsAppMessageStatusRequest,
        requestOptions?: MessagesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.WhatsappMessageStatusList>> {
        const { ruleset_id: rulesetId, per_page: perPage, starting_after: startingAfter } = request;
        const _queryParams: Record<string, string | string[] | object | object[] | null> = {};
        _queryParams.ruleset_id = rulesetId;
        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,
                "messages/status",
            ),
            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.WhatsappMessageStatusList,
                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 403:
                    throw new Intercom.unstable.ForbiddenError(
                        _response.error.body as Intercom.unstable.Error_,
                        _response.rawResponse,
                    );
                case 500:
                    throw new Intercom.unstable.InternalServerError(
                        _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", "/messages/status");
    }
}
