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

    export interface RequestOptions extends BaseRequestOptions {}
}

/**
 * Everything about your Data Attributes
 */
export class DataAttributesClient {
    protected readonly _options: NormalizedClientOptionsWithAuth<DataAttributesClient.Options>;

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

    /**
     * You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations.
     *
     * @param {Intercom.ListDataAttributesRequest} request
     * @param {DataAttributesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.dataAttributes.list({
     *         model: "contact",
     *         include_archived: true
     *     })
     */
    public list(
        request: Intercom.ListDataAttributesRequest = {},
        requestOptions?: DataAttributesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.DataAttributeList> {
        return core.HttpResponsePromise.fromPromise(this.__list(request, requestOptions));
    }

    private async __list(
        request: Intercom.ListDataAttributesRequest = {},
        requestOptions?: DataAttributesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.DataAttributeList>> {
        const { model, include_archived: includeArchived } = request;
        const _queryParams: Record<string, string | string[] | object | object[] | null> = {};
        if (model != null) {
            _queryParams.model = model;
        }

        if (includeArchived != null) {
            _queryParams.include_archived = includeArchived.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,
                "data_attributes",
            ),
            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.DataAttributeList, 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", "/data_attributes");
    }

    /**
     * You can create a data attributes for a `contact` or a `company`.
     *
     * @param {Intercom.CreateDataAttributeRequest} request
     * @param {DataAttributesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.BadRequestError}
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.dataAttributes.create({
     *         data_type: "string"
     *     })
     *
     * @example
     *     await client.dataAttributes.create({
     *         data_type: "integer"
     *     })
     *
     * @example
     *     await client.dataAttributes.create({
     *         options: [{
     *                 value: "1-10"
     *             }]
     *     })
     */
    public create(
        request: Intercom.CreateDataAttributeRequest,
        requestOptions?: DataAttributesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.DataAttribute> {
        return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));
    }

    private async __create(
        request: Intercom.CreateDataAttributeRequest,
        requestOptions?: DataAttributesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.DataAttribute>> {
        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,
                "data_attributes",
            ),
            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.DataAttribute, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 400:
                    throw new Intercom.BadRequestError(_response.error.body as unknown, _response.rawResponse);
                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, "POST", "/data_attributes");
    }

    /**
     *
     * You can update a data attribute.
     *
     * > 🚧 Updating the data type is not possible
     * >
     * > It is currently a dangerous action to execute changing a data attribute's type via the API. You will need to update the type via the UI instead.
     *
     * @param {Intercom.UpdateDataAttributeRequest} request
     * @param {DataAttributesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.BadRequestError}
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.NotFoundError}
     * @throws {@link Intercom.UnprocessableEntityError}
     *
     * @example
     *     await client.dataAttributes.update({
     *         data_attribute_id: 1,
     *         body: {
     *             options: [{
     *                     value: "1-10"
     *                 }, {
     *                     value: "11-20"
     *                 }]
     *         }
     *     })
     *
     * @example
     *     await client.dataAttributes.update({
     *         data_attribute_id: 1,
     *         body: {
     *             options: [{
     *                     value: "1-10"
     *                 }, {
     *                     value: "11-50"
     *                 }]
     *         }
     *     })
     *
     * @example
     *     await client.dataAttributes.update({
     *         data_attribute_id: 1,
     *         body: {
     *             "description": "Trying to archieve",
     *             "archived": true
     *         }
     *     })
     */
    public update(
        request: Intercom.UpdateDataAttributeRequest,
        requestOptions?: DataAttributesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.DataAttribute> {
        return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions));
    }

    private async __update(
        request: Intercom.UpdateDataAttributeRequest,
        requestOptions?: DataAttributesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.DataAttribute>> {
        const { data_attribute_id: dataAttributeId, 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,
                `data_attributes/${core.url.encodePathParam(dataAttributeId)}`,
            ),
            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.DataAttribute, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 400:
                    throw new Intercom.BadRequestError(_response.error.body as unknown, _response.rawResponse);
                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);
                case 422:
                    throw new Intercom.UnprocessableEntityError(_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",
            "/data_attributes/{data_attribute_id}",
        );
    }
}
