import { PostHog } from 'posthog-node';
import { localhostUrl, isCloud, isStaging, baseUrl } from '@nangohq/utils';
import { UserType } from '../utils/utils.js';
import errorManager, { ErrorSourceEnum } from './error.manager.js';
import accountService from '../services/account.service.js';
import environmentService from '../services/environment.service.js';
import userService from '../services/user.service.js';
import { LogActionEnum } from '../models/Telemetry.js';
import { NANGO_VERSION } from '../version.js';
export var AnalyticsTypes;
(function (AnalyticsTypes) {
    AnalyticsTypes["ACCOUNT_CREATED"] = "server:account_created";
    AnalyticsTypes["ACCOUNT_JOINED"] = "server:account_joined";
    AnalyticsTypes["API_CONNECTION_INSERTED"] = "server:api_key_connection_inserted";
    AnalyticsTypes["API_CONNECTION_UPDATED"] = "server:api_key_connection_updated";
    AnalyticsTypes["TBA_CONNECTION_INSERTED"] = "server:tba_connection_inserted";
    AnalyticsTypes["TBA_CONNECTION_UPDATED"] = "server:tba_connection_updated";
    AnalyticsTypes["TABLEAU_CONNECTION_INSERTED"] = "server:tableau_connection_inserted";
    AnalyticsTypes["TABLEAU_CONNECTION_UPDATED"] = "server:tableau_connection_updated";
    AnalyticsTypes["JWT_CONNECTION_INSERTED"] = "server:jwt_connection_inserted";
    AnalyticsTypes["JWT_CONNECTION_UPDATED"] = "server:jwt_connection_updated";
    AnalyticsTypes["BILL_CONNECTION_INSERTED"] = "server:bill_connection_inserted";
    AnalyticsTypes["BILL_CONNECTION_UPDATED"] = "server:bill_connection_updated";
    AnalyticsTypes["TWO_STEP_CONNECTION_INSERTED"] = "server:two_step_connection_inserted";
    AnalyticsTypes["TWO_STEP_CONNECTION_UPDATED"] = "server:two_step_connection_updated";
    AnalyticsTypes["SIGNATURE_CONNECTION_INSERTED"] = "server:signature_connection_inserted";
    AnalyticsTypes["SIGNATURE_CONNECTION_UPDATED"] = "server:signature_connection_updated";
    AnalyticsTypes["CONFIG_CREATED"] = "server:config_created";
    AnalyticsTypes["CONNECTION_INSERTED"] = "server:connection_inserted";
    AnalyticsTypes["CONNECTION_LIST_FETCHED"] = "server:connection_list_fetched";
    AnalyticsTypes["CONNECTION_UPDATED"] = "server:connection_updated";
    AnalyticsTypes["PRE_API_KEY_AUTH"] = "server:pre_api_key_auth";
    AnalyticsTypes["PRE_APP_AUTH"] = "server:pre_appauth";
    AnalyticsTypes["PRE_APP_STORE_AUTH"] = "server:pre_app_store_auth";
    AnalyticsTypes["PRE_BASIC_API_KEY_AUTH"] = "server:pre_basic_api_key_auth";
    AnalyticsTypes["PRE_UNAUTH"] = "server:pre_unauth";
    AnalyticsTypes["PRE_WS_OAUTH"] = "server:pre_ws_oauth";
    AnalyticsTypes["PRE_BILL_AUTH"] = "server:pre_bill_auth";
    AnalyticsTypes["PRE_TWO_STEP_AUTH"] = "server:pre_two_step_auth";
    AnalyticsTypes["PRE_OAUTH2_CC_AUTH"] = "server:pre_oauth2_cc_auth";
    AnalyticsTypes["PRE_TBA_AUTH"] = "server:pre_tba_auth";
    AnalyticsTypes["PRE_JWT_AUTH"] = "server:pre_jwt_auth";
    AnalyticsTypes["PRE_SIGNATURE_AUTH"] = "server:pre_signature_auth";
    AnalyticsTypes["RESOURCE_CAPPED_CONNECTION_CREATED"] = "server:resource_capped:connection_creation";
    AnalyticsTypes["RESOURCE_CAPPED_CONNECTION_IMPORTED"] = "server:resource_capped:connection_imported";
    AnalyticsTypes["RESOURCE_CAPPED_SCRIPT_ACTIVATE"] = "server:resource_capped:script_activate";
    AnalyticsTypes["RESOURCE_CAPPED_SCRIPT_DEPLOY_IS_DISABLED"] = "server:resource_capped:script_deploy_is_disabled";
    AnalyticsTypes["SYNC_DEPLOY_SUCCESS"] = "sync:deploy_succeeded";
    AnalyticsTypes["SYNC_PAUSE"] = "sync:command_pause";
    AnalyticsTypes["SYNC_RUN"] = "sync:command_run";
    AnalyticsTypes["SYNC_UNPAUSE"] = "sync:command_unpause";
    AnalyticsTypes["SYNC_CANCEL"] = "sync:command_cancel";
    AnalyticsTypes["UNAUTH_CONNECTION_INSERTED"] = "server:unauth_connection_inserted";
    AnalyticsTypes["UNAUTH_CONNECTION_UPDATED"] = "server:unauth_connection_updated";
    AnalyticsTypes["WEB_CONNECION_CREATED"] = "web:connection_created";
    AnalyticsTypes["WEB_ACCOUNT_SIGNUP"] = "web:account_signup";
})(AnalyticsTypes || (AnalyticsTypes = {}));
const AnalyticsEventMapping = {
    TWO_STEP: {
        creation: AnalyticsTypes.TWO_STEP_CONNECTION_INSERTED,
        override: AnalyticsTypes.TWO_STEP_CONNECTION_UPDATED
    },
    SIGNATURE: {
        creation: AnalyticsTypes.SIGNATURE_CONNECTION_INSERTED,
        override: AnalyticsTypes.SIGNATURE_CONNECTION_UPDATED
    },
    BILL: {
        creation: AnalyticsTypes.BILL_CONNECTION_INSERTED,
        override: AnalyticsTypes.BILL_CONNECTION_UPDATED
    },
    JWT: {
        creation: AnalyticsTypes.JWT_CONNECTION_INSERTED,
        override: AnalyticsTypes.JWT_CONNECTION_UPDATED
    },
    TABLEAU: {
        creation: AnalyticsTypes.TABLEAU_CONNECTION_INSERTED,
        override: AnalyticsTypes.TABLEAU_CONNECTION_UPDATED
    },
    TBA: {
        creation: AnalyticsTypes.TBA_CONNECTION_INSERTED,
        override: AnalyticsTypes.TBA_CONNECTION_UPDATED
    },
    API_KEY: {
        creation: AnalyticsTypes.API_CONNECTION_INSERTED,
        override: AnalyticsTypes.API_CONNECTION_UPDATED
    },
    BASIC: {
        creation: AnalyticsTypes.API_CONNECTION_INSERTED,
        override: AnalyticsTypes.API_CONNECTION_UPDATED
    }
};
class Analytics {
    client;
    packageVersion;
    constructor() {
        try {
            if (process.env['TELEMETRY']?.toLowerCase() !== 'false' && !isStaging) {
                this.client = new PostHog('phc_4S2pWFTyPYT1i7zwC8YYQqABvGgSAzNHubUkdEFvcTl');
                this.client.enable();
                this.packageVersion = NANGO_VERSION;
            }
        }
        catch (err) {
            errorManager.report(err, {
                source: ErrorSourceEnum.PLATFORM,
                operation: LogActionEnum.ANALYTICS
            });
        }
    }
    async track(name, accountId, eventProperties, userProperties) {
        try {
            if (this.client == null) {
                return;
            }
            eventProperties = eventProperties || {};
            userProperties = userProperties || {};
            const userType = this.getUserType(accountId, baseUrl);
            const userId = this.getUserIdWithType(userType, accountId, baseUrl);
            eventProperties['host'] = baseUrl;
            eventProperties['user-type'] = userType;
            eventProperties['user-account'] = userId;
            eventProperties['nango-server-version'] = this.packageVersion || 'unknown';
            if (isCloud && accountId != null) {
                const account = await accountService.getAccountById(accountId);
                if (account !== null && account.id !== undefined) {
                    const users = await userService.getUsersByAccountId(account.id);
                    if (users.length > 0) {
                        userProperties['email'] = users.map((user) => user.email).join(',');
                        userProperties['name'] = users.map((user) => user.name).join(',');
                    }
                }
            }
            userProperties['user-type'] = userType;
            userProperties['account'] = userId;
            eventProperties['$set'] = userProperties;
            this.client.capture({
                event: name,
                distinctId: userId,
                properties: eventProperties
            });
        }
        catch (err) {
            errorManager.report(err, {
                source: ErrorSourceEnum.PLATFORM,
                operation: LogActionEnum.ANALYTICS,
                accountId: accountId
            });
        }
    }
    async trackByEnvironmentId(name, environmentId, eventProperties, userProperties) {
        const accountId = await environmentService.getAccountIdFromEnvironment(environmentId);
        if (typeof accountId !== 'undefined' && accountId !== null) {
            return this.track(name, accountId, eventProperties, userProperties);
        }
    }
    getUserType(accountId, baseUrl) {
        if (baseUrl === localhostUrl) {
            return UserType.Local;
        }
        else if (accountId === 0) {
            return UserType.SelfHosted;
        }
        else {
            return UserType.Cloud;
        }
    }
    getUserIdWithType(userType, accountId, baseUrl) {
        switch (userType) {
            case UserType.Local:
                return `${userType}-local`;
            case UserType.SelfHosted:
                return `${userType}-${baseUrl}`;
            case UserType.Cloud:
                return `${userType}-${(accountId || 0).toString()}`;
            default:
                return 'unknown';
        }
    }
    async trackConnectionEvent({ provider_type, operation, accountId }) {
        const providerKey = provider_type;
        const eventType = AnalyticsEventMapping[providerKey][operation];
        await this.track(eventType, accountId, { provider_type });
    }
}
export default new Analytics();
//# sourceMappingURL=analytics.js.map