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

    export interface RequestOptions extends BaseRequestOptions {}
}

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

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

    /**
     * You can fetch a list of all articles by making a GET request to `https://api.intercom.io/articles`.
     *
     * > 📘 How are the articles sorted and ordered?
     * >
     * > Articles will be returned in descending order on the `updated_at` attribute. This means if you need to iterate through results then we'll show the most recently updated articles first.
     *
     * @param {Intercom.ListArticlesRequest} request
     * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.articles.list()
     */
    public async list(
        request: Intercom.ListArticlesRequest = {},
        requestOptions?: ArticlesClient.RequestOptions,
    ): Promise<core.Page<Intercom.ArticleListItem, Intercom.ArticleList>> {
        const list = core.HttpResponsePromise.interceptFunction(
            async (request: Intercom.ListArticlesRequest): Promise<core.WithRawResponse<Intercom.ArticleList>> => {
                const { page, per_page: perPage } = request;
                const _queryParams: Record<string, string | string[] | object | object[] | null> = {};
                if (page != null) {
                    _queryParams.page = page.toString();
                }
                if (perPage != null) {
                    _queryParams.per_page = perPage.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,
                        "articles",
                    ),
                    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.ArticleList, rawResponse: _response.rawResponse };
                }
                if (_response.error.reason === "status-code") {
                    switch (_response.error.statusCode) {
                        case 401:
                            throw new Intercom.UnauthorizedError(
                                _response.error.body as Intercom.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", "/articles");
            },
        );
        let _offset = request?.page != null ? request?.page : 1;
        const dataWithRawResponse = await list(request).withRawResponse();
        return new core.Page<Intercom.ArticleListItem, Intercom.ArticleList>({
            response: dataWithRawResponse.data,
            rawResponse: dataWithRawResponse.rawResponse,
            hasNextPage: (response) => (response?.data ?? []).length > 0,
            getItems: (response) => response?.data ?? [],
            loadPage: (_response) => {
                _offset += 1;
                return list(core.setObjectProperty(request, "page", _offset));
            },
        });
    }

    /**
     * You can create a new article by making a POST request to `https://api.intercom.io/articles`.
     *
     * @param {Intercom.CreateArticleRequest} request
     * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.BadRequestError}
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.articles.create({
     *         title: "Thanks for everything",
     *         description: "Description of the Article",
     *         body: "Body of the Article",
     *         author_id: 991267497,
     *         state: "published",
     *         parent_id: 145,
     *         parent_type: "collection",
     *         translated_content: {
     *             fr: {
     *                 title: "Merci pour tout",
     *                 description: "Description de l'article",
     *                 body: "Corps de l'article",
     *                 author_id: 991267497,
     *                 state: "published"
     *             }
     *         }
     *     })
     *
     * @example
     *     await client.articles.create({
     *         title: "Thanks for everything",
     *         description: "Description of the Article",
     *         body: "Body of the Article",
     *         author_id: 1295,
     *         state: "published"
     *     })
     */
    public create(
        request?: Intercom.CreateArticleRequest,
        requestOptions?: ArticlesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.Article> {
        return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));
    }

    private async __create(
        request?: Intercom.CreateArticleRequest,
        requestOptions?: ArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.Article>> {
        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,
                "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.Article, 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,
                    );
                default:
                    throw new errors.IntercomError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

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

    /**
     * You can fetch the details of a single article by making a GET request to `https://api.intercom.io/articles/<id>`.
     *
     * @param {Intercom.FindArticleRequest} request
     * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.articles.find({
     *         article_id: 1
     *     })
     */
    public find(
        request: Intercom.FindArticleRequest,
        requestOptions?: ArticlesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.Article> {
        return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions));
    }

    private async __find(
        request: Intercom.FindArticleRequest,
        requestOptions?: ArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.Article>> {
        const { article_id: articleId } = 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,
                `articles/${core.url.encodePathParam(articleId)}`,
            ),
            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.Article, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new Intercom.UnauthorizedError(
                        _response.error.body as Intercom.Error_,
                        _response.rawResponse,
                    );
                case 404:
                    throw new Intercom.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", "/articles/{article_id}");
    }

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

    private async __update(
        request: Intercom.UpdateArticleRequest,
        requestOptions?: ArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.Article>> {
        const { article_id: articleId, ..._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,
                `articles/${core.url.encodePathParam(articleId)}`,
            ),
            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.Article, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new Intercom.UnauthorizedError(
                        _response.error.body as Intercom.Error_,
                        _response.rawResponse,
                    );
                case 404:
                    throw new Intercom.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", "/articles/{article_id}");
    }

    /**
     * You can delete a single article by making a DELETE request to `https://api.intercom.io/articles/<id>`.
     *
     * @param {Intercom.DeleteArticleRequest} request
     * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.articles.delete({
     *         article_id: 1
     *     })
     */
    public delete(
        request: Intercom.DeleteArticleRequest,
        requestOptions?: ArticlesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.DeletedArticleObject> {
        return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions));
    }

    private async __delete(
        request: Intercom.DeleteArticleRequest,
        requestOptions?: ArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.DeletedArticleObject>> {
        const { article_id: articleId } = 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,
                `articles/${core.url.encodePathParam(articleId)}`,
            ),
            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.DeletedArticleObject, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new Intercom.UnauthorizedError(
                        _response.error.body as Intercom.Error_,
                        _response.rawResponse,
                    );
                case 404:
                    throw new Intercom.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", "/articles/{article_id}");
    }

    /**
     * You can search for articles by making a GET request to `https://api.intercom.io/articles/search`.
     *
     * @param {Intercom.SearchArticlesRequest} request
     * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.articles.search({
     *         phrase: "Getting started",
     *         state: "published",
     *         help_center_id: 1,
     *         highlight: true
     *     })
     */
    public search(
        request: Intercom.SearchArticlesRequest = {},
        requestOptions?: ArticlesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.ArticleSearchResponse> {
        return core.HttpResponsePromise.fromPromise(this.__search(request, requestOptions));
    }

    private async __search(
        request: Intercom.SearchArticlesRequest = {},
        requestOptions?: ArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.ArticleSearchResponse>> {
        const { phrase, state, help_center_id: helpCenterId, highlight } = request;
        const _queryParams: Record<string, string | string[] | object | object[] | null> = {};
        if (phrase != null) {
            _queryParams.phrase = phrase;
        }

        if (state != null) {
            _queryParams.state = state;
        }

        if (helpCenterId != null) {
            _queryParams.help_center_id = helpCenterId.toString();
        }

        if (highlight != null) {
            _queryParams.highlight = highlight.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,
                "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.ArticleSearchResponse, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new Intercom.UnauthorizedError(
                        _response.error.body as Intercom.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", "/articles/search");
    }
}
