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

    export interface RequestOptions extends BaseRequestOptions {}
}

/**
 * Everything about subscription types
 */
export class SubscriptionTypesClient {
    protected readonly _options: NormalizedClientOptionsWithAuth<SubscriptionTypesClient.Options>;

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

    /**
     * You can add a specific subscription to a contact. In Intercom, we have two different subscription types based on user consent - opt-out and opt-in:
     *
     *   1.Attaching a contact to an opt-out subscription type will opt that user out from receiving messages related to that subscription type.
     *
     *   2.Attaching a contact to an opt-in subscription type will opt that user in to receiving messages related to that subscription type.
     *
     * This will return a subscription type model for the subscription type that was added to the contact.
     *
     * @param {Intercom.unstable.AttachSubscriptionTypeToContactRequest} request
     * @param {SubscriptionTypesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.subscriptionTypes.attachSubscriptionTypeToContact({
     *         contact_id: "63a07ddf05a32042dffac965",
     *         id: "37846",
     *         consent_type: "opt_in"
     *     })
     *
     * @example
     *     await client.unstable.subscriptionTypes.attachSubscriptionTypeToContact({
     *         contact_id: "63a07ddf05a32042dffac965",
     *         id: "invalid_id",
     *         consent_type: "opt_in"
     *     })
     */
    public attachSubscriptionTypeToContact(
        request: Intercom.unstable.AttachSubscriptionTypeToContactRequest,
        requestOptions?: SubscriptionTypesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.SubscriptionType> {
        return core.HttpResponsePromise.fromPromise(this.__attachSubscriptionTypeToContact(request, requestOptions));
    }

    private async __attachSubscriptionTypeToContact(
        request: Intercom.unstable.AttachSubscriptionTypeToContactRequest,
        requestOptions?: SubscriptionTypesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.SubscriptionType>> {
        const { contact_id: contactId, ..._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,
                `contacts/${core.url.encodePathParam(contactId)}/subscriptions`,
            ),
            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.unstable.SubscriptionType, 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,
            "POST",
            "/contacts/{contact_id}/subscriptions",
        );
    }

    /**
     * You can remove a specific subscription from a contact. This will return a subscription type model for the subscription type that was removed from the contact.
     *
     * @param {Intercom.unstable.DetachSubscriptionTypeToContactRequest} request
     * @param {SubscriptionTypesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     * @throws {@link Intercom.unstable.NotFoundError}
     *
     * @example
     *     await client.unstable.subscriptionTypes.detachSubscriptionTypeToContact({
     *         contact_id: "63a07ddf05a32042dffac965",
     *         id: "37846"
     *     })
     */
    public detachSubscriptionTypeToContact(
        request: Intercom.unstable.DetachSubscriptionTypeToContactRequest,
        requestOptions?: SubscriptionTypesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.SubscriptionType> {
        return core.HttpResponsePromise.fromPromise(this.__detachSubscriptionTypeToContact(request, requestOptions));
    }

    private async __detachSubscriptionTypeToContact(
        request: Intercom.unstable.DetachSubscriptionTypeToContactRequest,
        requestOptions?: SubscriptionTypesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.SubscriptionType>> {
        const { contact_id: contactId, 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,
                `contacts/${core.url.encodePathParam(contactId)}/subscriptions/${core.url.encodePathParam(id)}`,
            ),
            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.unstable.SubscriptionType, 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,
            "DELETE",
            "/contacts/{contact_id}/subscriptions/{id}",
        );
    }

    /**
     * You can list all subscription types. A list of subscription type objects will be returned.
     *
     * @param {SubscriptionTypesClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link Intercom.unstable.UnauthorizedError}
     *
     * @example
     *     await client.unstable.subscriptionTypes.listSubscriptionTypes()
     */
    public listSubscriptionTypes(
        requestOptions?: SubscriptionTypesClient.RequestOptions,
    ): core.HttpResponsePromise<Intercom.unstable.SubscriptionTypeList> {
        return core.HttpResponsePromise.fromPromise(this.__listSubscriptionTypes(requestOptions));
    }

    private async __listSubscriptionTypes(
        requestOptions?: SubscriptionTypesClient.RequestOptions,
    ): Promise<core.WithRawResponse<Intercom.unstable.SubscriptionTypeList>> {
        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,
                "subscription_types",
            ),
            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.SubscriptionTypeList,
                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", "/subscription_types");
    }
}
