// 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 {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     *
     * @example
     *     await client.unstable.articles.listArticles()
     */
    public listArticles(
        requestOptions?: ArticlesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.ArticleList> {
        return core.HttpResponsePromise.fromPromise(this.__listArticles(requestOptions));
    }

    private async __listArticles(
        requestOptions?: ArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.ArticleList>> {
        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: 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.ArticleList, 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", "/articles");
    }

    /**
     * You can create a new article by making a POST request to `https://api.intercom.io/articles`.
     *
     * @param {unknown} request
     * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.BadRequestError}
     * @throws {@link Intercom.unstable.UnauthorizedError}
     *
     * @example
     *     await client.unstable.articles.createArticle({
     *         "key": "value"
     *     })
     */
    public createArticle(
        request?: unknown,
        requestOptions?: ArticlesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.Article> {
        return core.HttpResponsePromise.fromPromise(this.__createArticle(request, requestOptions));
    }

    private async __createArticle(
        request?: unknown,
        requestOptions?: ArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.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,
            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.Article, 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", "/articles");
    }

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

    private async __retrieveArticle(
        request: Intercom.unstable.RetrieveArticleRequest,
        requestOptions?: ArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.Article>> {
        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,
                `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.Article, 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", "/articles/{id}");
    }

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

    private async __deleteArticle(
        request: Intercom.unstable.DeleteArticleRequest,
        requestOptions?: ArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.DeletedArticleObject>> {
        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,
                `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.DeletedArticleObject,
                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", "/articles/{id}");
    }

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

    private async __searchArticles(
        request: Intercom.unstable.SearchArticlesRequest = {},
        requestOptions?: ArticlesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.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.unstable.ArticleSearchResponse,
                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", "/articles/search");
    }
}
