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

    export interface RequestOptions extends BaseRequestOptions {}
}

/**
 * Operations related to saved replies (macros) in conversations
 */
export class MacrosClient {
    protected readonly _options: NormalizedClientOptionsWithAuth<MacrosClient.Options>;

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

    /**
     * You can fetch a list of all macros (saved replies) in your workspace for use in automating responses.
     *
     * The macros are returned in descending order by updated_at.
     *
     * **Pagination**
     *
     * This endpoint uses cursor-based pagination via the `starting_after` parameter. The cursor is a Base64-encoded JSON array containing `[updated_at, id]` of the last item from the previous page.
     *
     * **Placeholder Transformation**
     *
     * The API transforms Intercom placeholders to a more standard XML-like format:
     * - From: `{{user.name | fallback: 'there'}}`
     * - To: `<attribute key="user.name" default="there"/>`
     *
     * @param {Intercom.unstable.ListMacrosRequest} request
     * @param {MacrosClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.BadRequestError}
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.ForbiddenError}
     *
     * @example
     *     await client.unstable.macros.listMacros({
     *         per_page: 1,
     *         starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd",
     *         updated_since: 1000000
     *     })
     */
    public listMacros(
        request: Intercom.unstable.ListMacrosRequest = {},
        requestOptions?: MacrosClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.MacroList> {
        return core.HttpResponsePromise.fromPromise(this.__listMacros(request, requestOptions));
    }

    private async __listMacros(
        request: Intercom.unstable.ListMacrosRequest = {},
        requestOptions?: MacrosClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.MacroList>> {
        const { per_page: perPage, starting_after: startingAfter, updated_since: updatedSince } = request;
        const _queryParams: Record<string, string | string[] | object | object[] | null> = {};
        if (perPage != null) {
            _queryParams.per_page = perPage.toString();
        }

        if (startingAfter != null) {
            _queryParams.starting_after = startingAfter;
        }

        if (updatedSince != null) {
            _queryParams.updated_since = updatedSince.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,
                "macros",
            ),
            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.MacroList, 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,
                    );
                default:
                    throw new errors.IntercomError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/macros");
    }

    /**
     * You can fetch a single macro (saved reply) by its ID. The macro will only be returned if it is visible to the authenticated user based on its visibility settings.
     *
     * **Visibility Rules**
     *
     * A macro is returned based on its `visible_to` setting:
     * - `everyone`: Always visible to all team members
     * - `specific_teams`: Only visible if the authenticated user belongs to one of the teams specified in `visible_to_team_ids`
     *
     * If a macro exists but is not visible to the authenticated user, a 404 error is returned.
     *
     * **Placeholder Transformation**
     *
     * The API transforms Intercom placeholders to a more standard XML-like format in the `body` field:
     * - From: `{{user.name | fallback: 'there'}}`
     * - To: `<attribute key="user.name" default="there"/>`
     *
     * Default values in placeholders are HTML-escaped for security.
     *
     * @param {Intercom.unstable.GetMacroRequest} request
     * @param {MacrosClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.ForbiddenError}
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.macros.getMacro({
     *         id: "123"
     *     })
     */
    public getMacro(
        request: Intercom.unstable.GetMacroRequest,
        requestOptions?: MacrosClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.Macro | undefined> {
        return core.HttpResponsePromise.fromPromise(this.__getMacro(request, requestOptions));
    }

    private async __getMacro(
        request: Intercom.unstable.GetMacroRequest,
        requestOptions?: MacrosClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.Macro | undefined>> {
        const { id } = request;
        const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
        const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
            _authRequest.headers,
            this._options?.headers,
            mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }),
            requestOptions?.headers,
        );
        const _response = await (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.IntercomEnvironment.UsProduction,
                `macros/${core.url.encodePathParam(id)}`,
            ),
            method: "GET",
            headers: _headers,
            queryParameters: requestOptions?.queryParams,
            timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000,
            maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
            fetchFn: this._options?.fetch,
            logging: this._options.logging,
        });
        if (_response.ok) {
            return { data: _response.body as Intercom.unstable.Macro | undefined, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new Intercom.unstable.UnauthorizedError(
                        _response.error.body as Intercom.unstable.Error_,
                        _response.rawResponse,
                    );
                case 403:
                    throw new Intercom.unstable.ForbiddenError(
                        _response.error.body as Intercom.unstable.Error_,
                        _response.rawResponse,
                    );
                case 404:
                    throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse);
                default:
                    throw new errors.IntercomError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/macros/{id}");
    }
}
