// 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 or an email.
     *
     * > 🚧 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.CreateMessageRequest} request
     * @param {MessagesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.BadRequestError}
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.ForbiddenError}
     * @throws {@link Intercom.UnprocessableEntityError}
     *
     * @example
     *     await client.messages.create({
     *         message_type: "email",
     *         subject: "Thanks for everything",
     *         body: "Hello there",
     *         template: "plain",
     *         from: {
     *             type: "admin",
     *             id: 394051
     *         },
     *         to: {
     *             type: "user",
     *             id: "536e564f316c83104c000020"
     *         }
     *     })
     *
     * @example
     *     await client.messages.create({
     *         message_type: "inapp",
     *         subject: "heyy",
     *         body: "Hello there",
     *         template: "plain",
     *         from: {
     *             type: "admin",
     *             id: 394051
     *         },
     *         to: {
     *             type: "user",
     *             id: "6762f23b1bb69f9f2193bc1a"
     *         },
     *         created_at: 1590000000,
     *         create_conversation_without_contact_reply: true
     *     })
     *
     * @example
     *     await client.messages.create({
     *         message_type: "email",
     *         subject: "Thanks for everything",
     *         body: "hey there",
     *         template: "plain",
     *         from: {
     *             type: "admin",
     *             id: 394051
     *         },
     *         to: {
     *             type: "user",
     *             id: "536e564f316c83104c000020"
     *         },
     *         created_at: 1590000000,
     *         create_conversation_without_contact_reply: true
     *     })
     *
     * @example
     *     await client.messages.create({
     *         message_type: "email",
     *         subject: "heyy",
     *         body: "Hello there",
     *         template: "plain",
     *         from: {
     *             type: "admin",
     *             id: 394051
     *         },
     *         to: {
     *             type: "user",
     *             id: "6762f23d1bb69f9f2193bc1c"
     *         },
     *         created_at: 1590000000,
     *         create_conversation_without_contact_reply: true
     *     })
     */
    public create(
        request?: Intercom.CreateMessageRequest,
        requestOptions?: MessagesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.Message> {
        return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));
    }

    private async __create(
        request?: Intercom.CreateMessageRequest,
        requestOptions?: MessagesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.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.Message, rawResponse: _response.rawResponse };
        }

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