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

    export interface RequestOptions extends BaseRequestOptions {}
}

/**
 * Everything about your Custom Object instances.
 * {% admonition type="warning" name="Permission Requirements" %}
 *   From now on, to access this endpoint, you need additional permissions. Please head over to the [Developer Hub](https://app.intercom.com/a/apps/_/developer-hub) app package authentication settings to configure the required permissions.
 * {% /admonition %}
 */
export class CustomObjectInstancesClient {
    protected readonly _options: NormalizedClientOptionsWithAuth<CustomObjectInstancesClient.Options>;

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

    /**
     * Fetch a Custom Object Instance by external_id.
     *
     * @param {Intercom.GetCustomObjectInstancesByExternalIdRequest} request
     * @param {CustomObjectInstancesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.customObjectInstances.getCustomObjectInstancesByExternalId({
     *         custom_object_type_identifier: "Order",
     *         external_id: "external_id"
     *     })
     */
    public getCustomObjectInstancesByExternalId(
        request: Intercom.GetCustomObjectInstancesByExternalIdRequest,
        requestOptions?: CustomObjectInstancesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.CustomObjectInstance | undefined> {
        return core.HttpResponsePromise.fromPromise(
            this.__getCustomObjectInstancesByExternalId(request, requestOptions),
        );
    }

    private async __getCustomObjectInstancesByExternalId(
        request: Intercom.GetCustomObjectInstancesByExternalIdRequest,
        requestOptions?: CustomObjectInstancesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.CustomObjectInstance | undefined>> {
        const { custom_object_type_identifier: customObjectTypeIdentifier, external_id: externalId } = request;
        const _queryParams: Record<string, string | string[] | object | object[] | null> = {};
        _queryParams.external_id = externalId;
        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,
                `custom_object_instances/${core.url.encodePathParam(customObjectTypeIdentifier)}`,
            ),
            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.CustomObjectInstance | undefined,
                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",
            "/custom_object_instances/{custom_object_type_identifier}",
        );
    }

    /**
     * Create or update a custom object instance
     *
     * @param {Intercom.CreateOrUpdateCustomObjectInstanceRequest} request
     * @param {CustomObjectInstancesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.customObjectInstances.createCustomObjectInstances({
     *         custom_object_type_identifier: "Order",
     *         external_id: "123",
     *         external_created_at: 1392036272,
     *         external_updated_at: 1392036272,
     *         custom_attributes: {
     *             "order_number": "ORDER-12345",
     *             "total_amount": "custom_attributes"
     *         }
     *     })
     */
    public createCustomObjectInstances(
        request: Intercom.CreateOrUpdateCustomObjectInstanceRequest,
        requestOptions?: CustomObjectInstancesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.CustomObjectInstance | undefined> {
        return core.HttpResponsePromise.fromPromise(this.__createCustomObjectInstances(request, requestOptions));
    }

    private async __createCustomObjectInstances(
        request: Intercom.CreateOrUpdateCustomObjectInstanceRequest,
        requestOptions?: CustomObjectInstancesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.CustomObjectInstance | undefined>> {
        const { custom_object_type_identifier: customObjectTypeIdentifier, ..._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,
                `custom_object_instances/${core.url.encodePathParam(customObjectTypeIdentifier)}`,
            ),
            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.CustomObjectInstance | undefined,
                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,
            "POST",
            "/custom_object_instances/{custom_object_type_identifier}",
        );
    }

    /**
     * Delete a single Custom Object instance by external_id.
     *
     * @param {Intercom.DeleteCustomObjectInstancesByIdRequest} request
     * @param {CustomObjectInstancesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.customObjectInstances.deleteCustomObjectInstancesById({
     *         custom_object_type_identifier: "Order",
     *         external_id: "external_id"
     *     })
     */
    public deleteCustomObjectInstancesById(
        request: Intercom.DeleteCustomObjectInstancesByIdRequest,
        requestOptions?: CustomObjectInstancesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.CustomObjectInstanceDeleted> {
        return core.HttpResponsePromise.fromPromise(this.__deleteCustomObjectInstancesById(request, requestOptions));
    }

    private async __deleteCustomObjectInstancesById(
        request: Intercom.DeleteCustomObjectInstancesByIdRequest,
        requestOptions?: CustomObjectInstancesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.CustomObjectInstanceDeleted>> {
        const { custom_object_type_identifier: customObjectTypeIdentifier, external_id: externalId } = request;
        const _queryParams: Record<string, string | string[] | object | object[] | null> = {};
        _queryParams.external_id = externalId;
        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,
                `custom_object_instances/${core.url.encodePathParam(customObjectTypeIdentifier)}`,
            ),
            method: "DELETE",
            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.CustomObjectInstanceDeleted, 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,
            "DELETE",
            "/custom_object_instances/{custom_object_type_identifier}",
        );
    }

    /**
     * Fetch a Custom Object Instance by id.
     *
     * @param {Intercom.GetCustomObjectInstancesByIdRequest} request
     * @param {CustomObjectInstancesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.customObjectInstances.getCustomObjectInstancesById({
     *         custom_object_type_identifier: "Order",
     *         custom_object_instance_id: "custom_object_instance_id"
     *     })
     */
    public getCustomObjectInstancesById(
        request: Intercom.GetCustomObjectInstancesByIdRequest,
        requestOptions?: CustomObjectInstancesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.CustomObjectInstance | undefined> {
        return core.HttpResponsePromise.fromPromise(this.__getCustomObjectInstancesById(request, requestOptions));
    }

    private async __getCustomObjectInstancesById(
        request: Intercom.GetCustomObjectInstancesByIdRequest,
        requestOptions?: CustomObjectInstancesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.CustomObjectInstance | undefined>> {
        const {
            custom_object_type_identifier: customObjectTypeIdentifier,
            custom_object_instance_id: customObjectInstanceId,
        } = 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,
                `custom_object_instances/${core.url.encodePathParam(customObjectTypeIdentifier)}/${core.url.encodePathParam(customObjectInstanceId)}`,
            ),
            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.CustomObjectInstance | undefined,
                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",
            "/custom_object_instances/{custom_object_type_identifier}/{custom_object_instance_id}",
        );
    }

    /**
     * Delete a single Custom Object instance using the Intercom defined id.
     *
     * @param {Intercom.DeleteCustomObjectInstancesByExternalIdRequest} request
     * @param {CustomObjectInstancesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     *
     * @example
     *     await client.customObjectInstances.deleteCustomObjectInstancesByExternalId({
     *         custom_object_type_identifier: "Order",
     *         custom_object_instance_id: "custom_object_instance_id"
     *     })
     */
    public deleteCustomObjectInstancesByExternalId(
        request: Intercom.DeleteCustomObjectInstancesByExternalIdRequest,
        requestOptions?: CustomObjectInstancesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.CustomObjectInstanceDeleted> {
        return core.HttpResponsePromise.fromPromise(
            this.__deleteCustomObjectInstancesByExternalId(request, requestOptions),
        );
    }

    private async __deleteCustomObjectInstancesByExternalId(
        request: Intercom.DeleteCustomObjectInstancesByExternalIdRequest,
        requestOptions?: CustomObjectInstancesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.CustomObjectInstanceDeleted>> {
        const {
            custom_object_type_identifier: customObjectTypeIdentifier,
            custom_object_instance_id: customObjectInstanceId,
        } = 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,
                `custom_object_instances/${core.url.encodePathParam(customObjectTypeIdentifier)}/${core.url.encodePathParam(customObjectInstanceId)}`,
            ),
            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.CustomObjectInstanceDeleted, 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,
            "DELETE",
            "/custom_object_instances/{custom_object_type_identifier}/{custom_object_instance_id}",
        );
    }
}
