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

    export interface RequestOptions extends BaseRequestOptions {}
}

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

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

    /**
     * You can fetch a list of all news items
     *
     * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     *
     * @example
     *     await client.unstable.news.listNewsItems()
     */
    public listNewsItems(
        requestOptions?: NewsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.PaginatedResponse> {
        return core.HttpResponsePromise.fromPromise(this.__listNewsItems(requestOptions));
    }

    private async __listNewsItems(
        requestOptions?: NewsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.PaginatedResponse>> {
        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,
                "news/news_items",
            ),
            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.PaginatedResponse, 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", "/news/news_items");
    }

    /**
     * You can create a news item
     *
     * @param {Intercom.unstable.NewsItemRequest} request
     * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     *
     * @example
     *     await client.unstable.news.createNewsItem({
     *         title: "Halloween is here!",
     *         body: "<p>New costumes in store for this spooky season</p>",
     *         sender_id: 991267834,
     *         state: "live",
     *         deliver_silently: true,
     *         labels: ["Product", "Update", "New"],
     *         reactions: ["\uD83D\uDE06", "\uD83D\uDE05"],
     *         newsfeed_assignments: [{
     *                 newsfeed_id: 53,
     *                 published_at: 1664638214
     *             }]
     *     })
     */
    public createNewsItem(
        request: Intercom.unstable.NewsItemRequest,
        requestOptions?: NewsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.NewsItem> {
        return core.HttpResponsePromise.fromPromise(this.__createNewsItem(request, requestOptions));
    }

    private async __createNewsItem(
        request: Intercom.unstable.NewsItemRequest,
        requestOptions?: NewsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.NewsItem>> {
        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,
                "news/news_items",
            ),
            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.NewsItem, 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, "POST", "/news/news_items");
    }

    /**
     * You can fetch the details of a single news item.
     *
     * @param {Intercom.unstable.RetrieveNewsItemRequest} request
     * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.news.retrieveNewsItem({
     *         id: 1
     *     })
     */
    public retrieveNewsItem(
        request: Intercom.unstable.RetrieveNewsItemRequest,
        requestOptions?: NewsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.NewsItem> {
        return core.HttpResponsePromise.fromPromise(this.__retrieveNewsItem(request, requestOptions));
    }

    private async __retrieveNewsItem(
        request: Intercom.unstable.RetrieveNewsItemRequest,
        requestOptions?: NewsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.NewsItem>> {
        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,
                `news/news_items/${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.NewsItem, 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", "/news/news_items/{id}");
    }

    /**
     * @param {Intercom.unstable.UpdateNewsItemRequest} request
     * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.news.updateNewsItem({
     *         id: 1,
     *         body: {
     *             title: "Christmas is here!",
     *             body: "<p>New gifts in store for the jolly season</p>",
     *             sender_id: 991267845,
     *             reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"]
     *         }
     *     })
     *
     * @example
     *     await client.unstable.news.updateNewsItem({
     *         id: 1,
     *         body: {
     *             title: "Christmas is here!",
     *             body: "<p>New gifts in store for the jolly season</p>",
     *             sender_id: 991267848,
     *             reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"]
     *         }
     *     })
     */
    public updateNewsItem(
        request: Intercom.unstable.UpdateNewsItemRequest,
        requestOptions?: NewsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.NewsItem> {
        return core.HttpResponsePromise.fromPromise(this.__updateNewsItem(request, requestOptions));
    }

    private async __updateNewsItem(
        request: Intercom.unstable.UpdateNewsItemRequest,
        requestOptions?: NewsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.NewsItem>> {
        const { id, body: _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,
                `news/news_items/${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.NewsItem, 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", "/news/news_items/{id}");
    }

    /**
     * You can delete a single news item.
     *
     * @param {Intercom.unstable.DeleteNewsItemRequest} request
     * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.news.deleteNewsItem({
     *         id: 1
     *     })
     */
    public deleteNewsItem(
        request: Intercom.unstable.DeleteNewsItemRequest,
        requestOptions?: NewsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.DeletedObject> {
        return core.HttpResponsePromise.fromPromise(this.__deleteNewsItem(request, requestOptions));
    }

    private async __deleteNewsItem(
        request: Intercom.unstable.DeleteNewsItemRequest,
        requestOptions?: NewsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.DeletedObject>> {
        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,
                `news/news_items/${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.DeletedObject, 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", "/news/news_items/{id}");
    }

    /**
     * You can fetch a list of all news items that are live on a given newsfeed
     *
     * @param {Intercom.unstable.ListLiveNewsfeedItemsRequest} request
     * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     *
     * @example
     *     await client.unstable.news.listLiveNewsfeedItems({
     *         id: "123"
     *     })
     */
    public listLiveNewsfeedItems(
        request: Intercom.unstable.ListLiveNewsfeedItemsRequest,
        requestOptions?: NewsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.PaginatedResponse> {
        return core.HttpResponsePromise.fromPromise(this.__listLiveNewsfeedItems(request, requestOptions));
    }

    private async __listLiveNewsfeedItems(
        request: Intercom.unstable.ListLiveNewsfeedItemsRequest,
        requestOptions?: NewsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.PaginatedResponse>> {
        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,
                `news/newsfeeds/${core.url.encodePathParam(id)}/items`,
            ),
            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.PaginatedResponse, 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", "/news/newsfeeds/{id}/items");
    }

    /**
     * You can fetch a list of all newsfeeds
     *
     * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     *
     * @example
     *     await client.unstable.news.listNewsfeeds()
     */
    public listNewsfeeds(
        requestOptions?: NewsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.PaginatedResponse> {
        return core.HttpResponsePromise.fromPromise(this.__listNewsfeeds(requestOptions));
    }

    private async __listNewsfeeds(
        requestOptions?: NewsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.PaginatedResponse>> {
        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,
                "news/newsfeeds",
            ),
            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.PaginatedResponse, 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", "/news/newsfeeds");
    }

    /**
     * You can fetch the details of a single newsfeed
     *
     * @param {Intercom.unstable.RetrieveNewsfeedRequest} request
     * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     *
     * @example
     *     await client.unstable.news.retrieveNewsfeed({
     *         id: "123"
     *     })
     */
    public retrieveNewsfeed(
        request: Intercom.unstable.RetrieveNewsfeedRequest,
        requestOptions?: NewsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.Newsfeed> {
        return core.HttpResponsePromise.fromPromise(this.__retrieveNewsfeed(request, requestOptions));
    }

    private async __retrieveNewsfeed(
        request: Intercom.unstable.RetrieveNewsfeedRequest,
        requestOptions?: NewsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.Newsfeed>> {
        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,
                `news/newsfeeds/${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.Newsfeed, 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", "/news/newsfeeds/{id}");
    }
}
