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

    export interface RequestOptions extends BaseRequestOptions {}
}

/**
 * Everything about your Internal Articles
 */
export class InternalArticlesClient {
    protected readonly _options: NormalizedClientOptionsWithAuth<InternalArticlesClient.Options>;

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

    /**
     * You can fetch a list of all internal articles by making a GET request to `https://api.intercom.io/internal_articles`.
     *
     * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     *
     * @example
     *     await client.unstable.internalArticles.listInternalArticles()
     */
    public listInternalArticles(
        requestOptions?: InternalArticlesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.InternalArticleList> {
        return core.HttpResponsePromise.fromPromise(this.__listInternalArticles(requestOptions));
    }

    private async __listInternalArticles(
        requestOptions?: InternalArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.InternalArticleList>> {
        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,
                "internal_articles",
            ),
            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.InternalArticleList,
                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,
                    );
                default:
                    throw new errors.IntercomError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

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

    /**
     * You can create a new internal article by making a POST request to `https://api.intercom.io/internal_articles`.
     *
     * @param {Intercom.unstable.CreateInternalArticleRequest} request
     * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.BadRequestError}
     * @throws {@link Intercom.unstable.UnauthorizedError}
     *
     * @example
     *     await client.unstable.internalArticles.createInternalArticle({
     *         title: "Thanks for everything",
     *         body: "Body of the Article",
     *         author_id: 991266252,
     *         owner_id: 991266252
     *     })
     *
     * @example
     *     await client.unstable.internalArticles.createInternalArticle({
     *         title: "Thanks for everything",
     *         body: "Body of the Internal Article",
     *         author_id: 1295,
     *         owner_id: 1295
     *     })
     */
    public createInternalArticle(
        request?: Intercom.unstable.CreateInternalArticleRequest,
        requestOptions?: InternalArticlesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.InternalArticle> {
        return core.HttpResponsePromise.fromPromise(this.__createInternalArticle(request, requestOptions));
    }

    private async __createInternalArticle(
        request?: Intercom.unstable.CreateInternalArticleRequest,
        requestOptions?: InternalArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.InternalArticle>> {
        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,
                "internal_articles",
            ),
            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.InternalArticle, 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,
                    );
                default:
                    throw new errors.IntercomError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/internal_articles");
    }

    /**
     * You can fetch the details of a single internal article by making a GET request to `https://api.intercom.io/internal_articles/<id>`.
     *
     * @param {Intercom.unstable.RetrieveInternalArticleRequest} request
     * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.internalArticles.retrieveInternalArticle({
     *         id: 1
     *     })
     */
    public retrieveInternalArticle(
        request: Intercom.unstable.RetrieveInternalArticleRequest,
        requestOptions?: InternalArticlesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.InternalArticle> {
        return core.HttpResponsePromise.fromPromise(this.__retrieveInternalArticle(request, requestOptions));
    }

    private async __retrieveInternalArticle(
        request: Intercom.unstable.RetrieveInternalArticleRequest,
        requestOptions?: InternalArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.InternalArticle>> {
        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,
                `internal_articles/${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.InternalArticle, 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 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", "/internal_articles/{id}");
    }

    /**
     * You can update the details of a single internal article by making a PUT request to `https://api.intercom.io/internal_articles/<id>`.
     *
     * @param {Intercom.unstable.UpdateInternalArticleRequestBody} request
     * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.internalArticles.updateInternalArticle({
     *         id: 1,
     *         title: "Christmas is here!",
     *         body: "<p>New gifts in store for the jolly season</p>"
     *     })
     */
    public updateInternalArticle(
        request: Intercom.unstable.UpdateInternalArticleRequestBody,
        requestOptions?: InternalArticlesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.InternalArticle> {
        return core.HttpResponsePromise.fromPromise(this.__updateInternalArticle(request, requestOptions));
    }

    private async __updateInternalArticle(
        request: Intercom.unstable.UpdateInternalArticleRequestBody,
        requestOptions?: InternalArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.InternalArticle>> {
        const { id, ..._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,
                `internal_articles/${core.url.encodePathParam(id)}`,
            ),
            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.unstable.InternalArticle, 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 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, "PUT", "/internal_articles/{id}");
    }

    /**
     * You can delete a single internal article by making a DELETE request to `https://api.intercom.io/internal_articles/<id>`.
     *
     * @param {Intercom.unstable.DeleteInternalArticleRequest} request
     * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.internalArticles.deleteInternalArticle({
     *         id: 1
     *     })
     */
    public deleteInternalArticle(
        request: Intercom.unstable.DeleteInternalArticleRequest,
        requestOptions?: InternalArticlesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.DeletedInternalArticleObject> {
        return core.HttpResponsePromise.fromPromise(this.__deleteInternalArticle(request, requestOptions));
    }

    private async __deleteInternalArticle(
        request: Intercom.unstable.DeleteInternalArticleRequest,
        requestOptions?: InternalArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.DeletedInternalArticleObject>> {
        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,
                `internal_articles/${core.url.encodePathParam(id)}`,
            ),
            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.unstable.DeletedInternalArticleObject,
                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 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, "DELETE", "/internal_articles/{id}");
    }

    /**
     * You can search for internal articles by making a GET request to `https://api.intercom.io/internal_articles/search`.
     *
     * @param {Intercom.unstable.SearchInternalArticlesRequest} request
     * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     *
     * @example
     *     await client.unstable.internalArticles.searchInternalArticles({
     *         folder_id: "folder_id"
     *     })
     */
    public searchInternalArticles(
        request: Intercom.unstable.SearchInternalArticlesRequest = {},
        requestOptions?: InternalArticlesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.InternalArticleSearchResponse> {
        return core.HttpResponsePromise.fromPromise(this.__searchInternalArticles(request, requestOptions));
    }

    private async __searchInternalArticles(
        request: Intercom.unstable.SearchInternalArticlesRequest = {},
        requestOptions?: InternalArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.InternalArticleSearchResponse>> {
        const { folder_id: folderId } = request;
        const _queryParams: Record<string, string | string[] | object | object[] | null> = {};
        if (folderId != null) {
            _queryParams.folder_id = folderId;
        }

        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,
                "internal_articles/search",
            ),
            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.InternalArticleSearchResponse,
                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,
                    );
                default:
                    throw new errors.IntercomError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

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