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

    export interface RequestOptions extends BaseRequestOptions {}
}

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

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

    /**
     * You can fetch the details of a single visitor.
     *
     * @param {Intercom.unstable.RetrieveVisitorWithUserIdRequest} request
     * @param {VisitorsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.visitors.retrieveVisitorWithUserId({
     *         user_id: "user_id"
     *     })
     */
    public retrieveVisitorWithUserId(
        request: Intercom.unstable.RetrieveVisitorWithUserIdRequest,
        requestOptions?: VisitorsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.Visitor | undefined> {
        return core.HttpResponsePromise.fromPromise(this.__retrieveVisitorWithUserId(request, requestOptions));
    }

    private async __retrieveVisitorWithUserId(
        request: Intercom.unstable.RetrieveVisitorWithUserIdRequest,
        requestOptions?: VisitorsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.Visitor | undefined>> {
        const { user_id: userId } = request;
        const _queryParams: Record<string, string | string[] | object | object[] | null> = {};
        _queryParams.user_id = userId;
        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,
                "visitors",
            ),
            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.unstable.Visitor | undefined,
                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", "/visitors");
    }

    /**
     * Sending a PUT request to `/visitors` will result in an update of an existing Visitor.
     *
     * **Option 1.** You can update a visitor by passing in the `user_id` of the visitor in the Request body.
     *
     * **Option 2.** You can update a visitor by passing in the `id` of the visitor in the Request body.
     *
     * @param {Intercom.UpdateVisitorRequestOne} request
     * @param {VisitorsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.visitors.updateVisitor({
     *         "id": "6762f30c1bb69f9f2193bc5e",
     *         "name": "Gareth Bale"
     *     })
     *
     * @example
     *     await client.unstable.visitors.updateVisitor({
     *         "user_id": "fail",
     *         "name": "Christian Fail"
     *     })
     */
    public updateVisitor(
        request?: Intercom.UpdateVisitorRequestOne,
        requestOptions?: VisitorsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.Visitor | undefined> {
        return core.HttpResponsePromise.fromPromise(this.__updateVisitor(request, requestOptions));
    }

    private async __updateVisitor(
        request?: Intercom.UpdateVisitorRequestOne,
        requestOptions?: VisitorsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.Visitor | undefined>> {
        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,
                "visitors",
            ),
            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.unstable.Visitor | undefined,
                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, "PUT", "/visitors");
    }

    /**
     * You can merge a Visitor to a Contact of role type `lead` or `user`.
     *
     * > 📘 What happens upon a visitor being converted?
     * >
     * > If the User exists, then the Visitor will be merged into it, the Visitor deleted and the User returned. If the User does not exist, the Visitor will be converted to a User, with the User identifiers replacing it's Visitor identifiers.
     *
     * @param {Intercom.unstable.ConvertVisitorRequest} request
     * @param {VisitorsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     *
     * @example
     *     await client.unstable.visitors.convertVisitor({
     *         type: "user",
     *         user: {
     *             "email": "foo@bar.com"
     *         },
     *         visitor: {
     *             "user_id": "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3"
     *         }
     *     })
     */
    public convertVisitor(
        request: Intercom.unstable.ConvertVisitorRequest,
        requestOptions?: VisitorsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.Contact> {
        return core.HttpResponsePromise.fromPromise(this.__convertVisitor(request, requestOptions));
    }

    private async __convertVisitor(
        request: Intercom.unstable.ConvertVisitorRequest,
        requestOptions?: VisitorsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.Contact>> {
        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,
                "visitors/convert",
            ),
            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.unstable.Contact, 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,
                    );
                default:
                    throw new errors.IntercomError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/visitors/convert");
    }
}
