// 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";
import { CollectionsClient } from "../resources/collections/client/Client.js";

export declare namespace HelpCentersClient {
    export interface Options extends BaseClientOptions {}

    export interface RequestOptions extends BaseRequestOptions {}
}

export class HelpCentersClient {
    protected readonly _options: NormalizedClientOptionsWithAuth<HelpCentersClient.Options>;
    protected _collections: CollectionsClient | undefined;

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

    public get collections(): CollectionsClient {
        return (this._collections ??= new CollectionsClient(this._options));
    }

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

    private async __find(
        request: Intercom.FindHelpCenterRequest,
        requestOptions?: HelpCentersClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.HelpCenter>> {
        const { help_center_id: helpCenterId } = 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,
                `help_center/help_centers/${core.url.encodePathParam(helpCenterId)}`,
            ),
            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.HelpCenter, 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",
            "/help_center/help_centers/{help_center_id}",
        );
    }

    /**
     * You can list all Help Centers by making a GET request to `https://api.intercom.io/help_center/help_centers`.
     *
     * @param {Intercom.ListHelpCentersRequest} request
     * @param {HelpCentersClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.helpCenters.list()
     */
    public async list(
        request: Intercom.ListHelpCentersRequest = {},
        requestOptions?: HelpCentersClient.RequestOptions,
    ): Promise<core.Page<Intercom.HelpCenter, Intercom.HelpCenterList>> {
        const list = core.HttpResponsePromise.interceptFunction(
            async (
                request: Intercom.ListHelpCentersRequest,
            ): Promise<core.WithRawResponse<Intercom.HelpCenterList>> => {
                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,
                        "help_center/help_centers",
                    ),
                    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.HelpCenterList, 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",
                    "/help_center/help_centers",
                );
            },
        );
        let _offset = request?.page != null ? request?.page : 1;
        const dataWithRawResponse = await list(request).withRawResponse();
        return new core.Page<Intercom.HelpCenter, Intercom.HelpCenterList>({
            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));
            },
        });
    }
}
