// 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 company.
     *
     * @param {Intercom.unstable.ListCompanyNotesRequest} request
     * @param {NotesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.notes.listCompanyNotes({
     *         id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632"
     *     })
     */
    public listCompanyNotes(
        request: Intercom.unstable.ListCompanyNotesRequest,
        requestOptions?: NotesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.NoteList> {
        return core.HttpResponsePromise.fromPromise(this.__listCompanyNotes(request, requestOptions));
    }

    private async __listCompanyNotes(
        request: Intercom.unstable.ListCompanyNotesRequest,
        requestOptions?: NotesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.NoteList>> {
        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,
                `companies/${core.url.encodePathParam(id)}/notes`,
            ),
            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.NoteList, rawResponse: _response.rawResponse };
        }

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

    /**
     * You can fetch a list of notes that are associated to a contact.
     *
     * @param {Intercom.unstable.ListNotesRequest} request
     * @param {NotesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.notes.listNotes({
     *         id: 1
     *     })
     */
    public listNotes(
        request: Intercom.unstable.ListNotesRequest,
        requestOptions?: NotesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.NoteList> {
        return core.HttpResponsePromise.fromPromise(this.__listNotes(request, requestOptions));
    }

    private async __listNotes(
        request: Intercom.unstable.ListNotesRequest,
        requestOptions?: NotesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.NoteList>> {
        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,
                `contacts/${core.url.encodePathParam(id)}/notes`,
            ),
            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.NoteList, rawResponse: _response.rawResponse };
        }

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

    /**
     * You can add a note to a single contact.
     *
     * @param {Intercom.unstable.CreateNoteRequest} request
     * @param {NotesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.notes.createNote({
     *         id: 1,
     *         body: "Hello",
     *         contact_id: "6762f0ad1bb69f9f2193bb62",
     *         admin_id: "123"
     *     })
     *
     * @example
     *     await client.unstable.notes.createNote({
     *         id: 1,
     *         body: "Hello",
     *         contact_id: "6762f0af1bb69f9f2193bb63",
     *         admin_id: "123"
     *     })
     *
     * @example
     *     await client.unstable.notes.createNote({
     *         id: 1,
     *         body: "Hello",
     *         contact_id: "123",
     *         admin_id: "123"
     *     })
     */
    public createNote(
        request: Intercom.unstable.CreateNoteRequest,
        requestOptions?: NotesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.Note> {
        return core.HttpResponsePromise.fromPromise(this.__createNote(request, requestOptions));
    }

    private async __createNote(
        request: Intercom.unstable.CreateNoteRequest,
        requestOptions?: NotesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.Note>> {
        const { id, ..._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(id)}/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.unstable.Note, rawResponse: _response.rawResponse };
        }

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

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

    private async __retrieveNote(
        request: Intercom.unstable.RetrieveNoteRequest,
        requestOptions?: NotesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.Note>> {
        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,
                `notes/${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.Note, 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", "/notes/{id}");
    }
}
