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

    export interface RequestOptions extends BaseRequestOptions {}
}

/**
 * Manage IP allowlist settings for your workspace.
 *
 * The IP Allowlist API allows you to configure which IP addresses are allowed to access the Intercom API and web application for your workspace. This is useful for restricting access to your Intercom workspace to specific corporate networks or VPNs.
 *
 * {% admonition type="info" name="Authentication" %}
 *   This endpoint requires the `manage_ip_allowlist` OAuth scope.
 * {% /admonition %}
 */
export class IpAllowlistClient {
    protected readonly _options: NormalizedClientOptionsWithAuth<IpAllowlistClient.Options>;

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

    /**
     * Retrieve the current IP allowlist configuration for the workspace.
     *
     * @param {IpAllowlistClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     *
     * @example
     *     await client.ipAllowlist.getIpAllowlist()
     */
    public getIpAllowlist(
        requestOptions?: IpAllowlistClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.IpAllowlist> {
        return core.HttpResponsePromise.fromPromise(this.__getIpAllowlist(requestOptions));
    }

    private async __getIpAllowlist(
        requestOptions?: IpAllowlistClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.IpAllowlist>> {
        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,
                "ip_allowlist",
            ),
            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.IpAllowlist, 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", "/ip_allowlist");
    }

    /**
     * Update the IP allowlist configuration for the workspace.
     *
     * {% admonition type="warning" name="Lockout Protection" %}
     *   The API will reject updates that would lock out the caller's IP address. Ensure your current IP is included in the allowlist when enabling the feature.
     * {% /admonition %}
     *
     * @param {Intercom.IpAllowlist} request
     * @param {IpAllowlistClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.UnauthorizedError}
     * @throws {@link Intercom.UnprocessableEntityError}
     *
     * @example
     *     await client.ipAllowlist.updateIpAllowlist({
     *         enabled: true,
     *         ip_allowlist: ["192.168.1.0/24", "10.0.0.1"]
     *     })
     */
    public updateIpAllowlist(
        request: Intercom.IpAllowlist,
        requestOptions?: IpAllowlistClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.IpAllowlist> {
        return core.HttpResponsePromise.fromPromise(this.__updateIpAllowlist(request, requestOptions));
    }

    private async __updateIpAllowlist(
        request: Intercom.IpAllowlist,
        requestOptions?: IpAllowlistClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.IpAllowlist>> {
        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,
                "ip_allowlist",
            ),
            method: "PUT",
            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.IpAllowlist, 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 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", "/ip_allowlist");
    }
}
