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

    export interface RequestOptions extends BaseRequestOptions {}
}

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

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

    /**
     *
     * You can view the currently authorised admin along with the embedded app object (a "workspace" in legacy terminology).
     *
     * > 🚧 Single Sign On
     * >
     * > If you are building a custom "Log in with Intercom" flow for your site, and you call the `/me` endpoint to identify the logged-in user, you should not accept any sign-ins from users with unverified email addresses as it poses a potential impersonation security risk.
     *
     * @param {AdminsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.unstable.admins.identifyAdmin()
     */
    public identifyAdmin(
        requestOptions?: AdminsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.AdminWithApp | undefined> {
        return core.HttpResponsePromise.fromPromise(this.__identifyAdmin(requestOptions));
    }

    private async __identifyAdmin(
        requestOptions?: AdminsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.AdminWithApp | 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,
                "me",
            ),
            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.AdminWithApp | undefined,
                rawResponse: _response.rawResponse,
            };
        }

        if (_response.error.reason === "status-code") {
            throw new errors.IntercomError({
                statusCode: _response.error.statusCode,
                body: _response.error.body,
                rawResponse: _response.rawResponse,
            });
        }

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/me");
    }

    /**
     * You can set an Admin as away for the Inbox.
     *
     * @param {Intercom.unstable.SetAwayAdminRequest} request
     * @param {AdminsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.BadRequestError}
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.admins.setAwayAdmin({
     *         id: 1,
     *         away_mode_enabled: true,
     *         away_mode_reassign: true,
     *         away_status_reason_id: 12345
     *     })
     *
     * @example
     *     await client.unstable.admins.setAwayAdmin({
     *         id: 1,
     *         away_mode_enabled: true,
     *         away_mode_reassign: true
     *     })
     */
    public setAwayAdmin(
        request: Intercom.unstable.SetAwayAdminRequest,
        requestOptions?: AdminsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.Admin | undefined> {
        return core.HttpResponsePromise.fromPromise(this.__setAwayAdmin(request, requestOptions));
    }

    private async __setAwayAdmin(
        request: Intercom.unstable.SetAwayAdminRequest,
        requestOptions?: AdminsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.Admin | undefined>> {
        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,
                `admins/${core.url.encodePathParam(id)}/away`,
            ),
            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.unstable.Admin | undefined, rawResponse: _response.rawResponse };
        }

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

    /**
     * You can get a log of activities by all admins in an app.
     *
     * @param {Intercom.unstable.ListActivityLogsRequest} request
     * @param {AdminsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     *
     * @example
     *     await client.unstable.admins.listActivityLogs({
     *         created_at_after: "1677253093",
     *         created_at_before: "1677861493"
     *     })
     */
    public listActivityLogs(
        request: Intercom.unstable.ListActivityLogsRequest,
        requestOptions?: AdminsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.ActivityLogList> {
        return core.HttpResponsePromise.fromPromise(this.__listActivityLogs(request, requestOptions));
    }

    private async __listActivityLogs(
        request: Intercom.unstable.ListActivityLogsRequest,
        requestOptions?: AdminsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.ActivityLogList>> {
        const { created_at_after: createdAtAfter, created_at_before: createdAtBefore } = request;
        const _queryParams: Record<string, string | string[] | object | object[] | null> = {};
        _queryParams.created_at_after = createdAtAfter;
        if (createdAtBefore != null) {
            _queryParams.created_at_before = createdAtBefore;
        }

        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,
                "admins/activity_logs",
            ),
            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.ActivityLogList, 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, "GET", "/admins/activity_logs");
    }

    /**
     * You can fetch a list of admins for a given workspace.
     *
     * @param {AdminsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     *
     * @example
     *     await client.unstable.admins.listAdmins()
     */
    public listAdmins(
        requestOptions?: AdminsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.AdminList> {
        return core.HttpResponsePromise.fromPromise(this.__listAdmins(requestOptions));
    }

    private async __listAdmins(
        requestOptions?: AdminsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.AdminList>> {
        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,
                "admins",
            ),
            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.AdminList, 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, "GET", "/admins");
    }

    /**
     * You can retrieve the details of a single admin.
     *
     * @param {Intercom.unstable.RetrieveAdminRequest} request
     * @param {AdminsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.admins.retrieveAdmin({
     *         id: 1
     *     })
     */
    public retrieveAdmin(
        request: Intercom.unstable.RetrieveAdminRequest,
        requestOptions?: AdminsClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.Admin | undefined> {
        return core.HttpResponsePromise.fromPromise(this.__retrieveAdmin(request, requestOptions));
    }

    private async __retrieveAdmin(
        request: Intercom.unstable.RetrieveAdminRequest,
        requestOptions?: AdminsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.Admin | undefined>> {
        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,
                `admins/${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.Admin | 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", "/admins/{id}");
    }
}
