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

    export interface RequestOptions extends BaseRequestOptions {}
}

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

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

    /**
     * You can fetch a list of notes that are associated to a contact.
     *
     * @param {Intercom.ListContactNotesRequest} request
     * @param {NotesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.notes.list({
     *         contact_id: "contact_id"
     *     })
     */
    public async list(
        request: Intercom.ListContactNotesRequest,
        requestOptions?: NotesClient.RequestOptions,
    ): Promise<core.Page<Intercom.Note, Intercom.NoteList>> {
        const list = core.HttpResponsePromise.interceptFunction(
            async (request: Intercom.ListContactNotesRequest): Promise<core.WithRawResponse<Intercom.NoteList>> => {
                const { contact_id: contactId, 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,
                        `contacts/${core.url.encodePathParam(contactId)}/notes`,
                    ),
                    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.NoteList, rawResponse: _response.rawResponse };
                }
                if (_response.error.reason === "status-code") {
                    switch (_response.error.statusCode) {
                        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",
                    "/contacts/{contact_id}/notes",
                );
            },
        );
        let _offset = request?.page != null ? request?.page : 1;
        const dataWithRawResponse = await list(request).withRawResponse();
        return new core.Page<Intercom.Note, Intercom.NoteList>({
            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 add a note to a single contact.
     *
     * @param {Intercom.CreateContactNoteRequest} request
     * @param {NotesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.notes.create({
     *         contact_id: "123",
     *         body: "Hello",
     *         admin_id: "123"
     *     })
     */
    public create(
        request: Intercom.CreateContactNoteRequest,
        requestOptions?: NotesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.Note> {
        return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));
    }

    private async __create(
        request: Intercom.CreateContactNoteRequest,
        requestOptions?: NotesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.Note>> {
        const { contact_id: contactId, ..._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,
                `contacts/${core.url.encodePathParam(contactId)}/notes`,
            ),
            method: "POST",
            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.Note, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                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, "POST", "/contacts/{contact_id}/notes");
    }

    /**
     * You can fetch the details of a single note.
     *
     * @param {Intercom.FindNoteRequest} request
     * @param {NotesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.notes.find({
     *         note_id: 1
     *     })
     */
    public find(
        request: Intercom.FindNoteRequest,
        requestOptions?: NotesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.Note> {
        return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions));
    }

    private async __find(
        request: Intercom.FindNoteRequest,
        requestOptions?: NotesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.Note>> {
        const { note_id: noteId } = 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,
                `notes/${core.url.encodePathParam(noteId)}`,
            ),
            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.Note, 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", "/notes/{note_id}");
    }
}
