"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InstanceStatsService = void 0;
const js_sha256_1 = require("js-sha256");
const types_1 = require("../../types");
const util_1 = require("../../util");
class InstanceStatsService {
    constructor({ featureToggleStore, userStore, projectStore, environmentStore, strategyStore, contextFieldStore, groupStore, segmentStore, roleStore, settingStore, clientInstanceStore, eventStore, apiTokenStore, clientMetricsStoreV2, }, { getLogger }, versionService, getActiveUsers, getProductionChanges) {
        this.strategyStore = strategyStore;
        this.userStore = userStore;
        this.featureToggleStore = featureToggleStore;
        this.environmentStore = environmentStore;
        this.projectStore = projectStore;
        this.groupStore = groupStore;
        this.contextFieldStore = contextFieldStore;
        this.segmentStore = segmentStore;
        this.roleStore = roleStore;
        this.versionService = versionService;
        this.settingStore = settingStore;
        this.eventStore = eventStore;
        this.clientInstanceStore = clientInstanceStore;
        this.logger = getLogger('services/stats-service.js');
        this.getActiveUsers = getActiveUsers;
        this.getProductionChanges = getProductionChanges;
        this.apiTokenStore = apiTokenStore;
        this.clientMetricsStore = clientMetricsStoreV2;
    }
    async refreshAppCountSnapshot() {
        try {
            this.appCount = await this.getLabeledAppCounts();
            return this.appCount;
        }
        catch (error) {
            this.logger.warn('Unable to retrieve statistics. This will be retried', error);
            return {
                '7d': 0,
                '30d': 0,
                allTime: 0,
            };
        }
    }
    getProjectModeCount() {
        return this.projectStore.getProjectModeCounts();
    }
    getToggleCount() {
        return this.featureToggleStore.count({
            archived: false,
        });
    }
    getArchivedToggleCount() {
        return this.featureToggleStore.count({
            archived: true,
        });
    }
    async hasOIDC() {
        const settings = await this.settingStore.get('unleash.enterprise.auth.oidc');
        return settings?.enabled || false;
    }
    async hasSAML() {
        const settings = await this.settingStore.get('unleash.enterprise.auth.saml');
        return settings?.enabled || false;
    }
    /**
     * use getStatsSnapshot for low latency, sacrificing data-freshness
     */
    async getStats() {
        const versionInfo = await this.versionService.getVersionInfo();
        const [featureToggles, archivedFeatureToggles, users, serviceAccounts, apiTokens, activeUsers, projects, contextFields, groups, roles, customRootRoles, customRootRolesInUse, environments, segments, strategies, SAMLenabled, OIDCenabled, clientApps, featureExports, featureImports, productionChanges, previousDayMetricsBucketsCount,] = await Promise.all([
            this.getToggleCount(),
            this.getArchivedToggleCount(),
            this.userStore.count(),
            this.userStore.countServiceAccounts(),
            this.apiTokenStore.countByType(),
            this.getActiveUsers(),
            this.getProjectModeCount(),
            this.contextFieldStore.count(),
            this.groupStore.count(),
            this.roleStore.count(),
            this.roleStore.filteredCount({ type: util_1.CUSTOM_ROOT_ROLE_TYPE }),
            this.roleStore.filteredCountInUse({ type: util_1.CUSTOM_ROOT_ROLE_TYPE }),
            this.environmentStore.count(),
            this.segmentStore.count(),
            this.strategyStore.count(),
            this.hasSAML(),
            this.hasOIDC(),
            this.appCount ? this.appCount : this.refreshAppCountSnapshot(),
            this.eventStore.filteredCount({ type: types_1.FEATURES_EXPORTED }),
            this.eventStore.filteredCount({ type: types_1.FEATURES_IMPORTED }),
            this.getProductionChanges(),
            this.clientMetricsStore.countPreviousDayHourlyMetricsBuckets(),
        ]);
        return {
            timestamp: new Date(),
            instanceId: versionInfo.instanceId,
            versionOSS: versionInfo.current.oss,
            versionEnterprise: versionInfo.current.enterprise,
            users,
            serviceAccounts,
            apiTokens,
            activeUsers,
            featureToggles,
            archivedFeatureToggles,
            projects,
            contextFields,
            roles,
            customRootRoles,
            customRootRolesInUse,
            groups,
            environments,
            segments,
            strategies,
            SAMLenabled,
            OIDCenabled,
            clientApps: Object.entries(clientApps).map(([range, count]) => ({
                range: range,
                count,
            })),
            featureExports,
            featureImports,
            productionChanges,
            previousDayMetricsBucketsCount,
        };
    }
    async getLabeledAppCounts() {
        const [t7d, t30d, allTime] = await Promise.all([
            this.clientInstanceStore.getDistinctApplicationsCount(7),
            this.clientInstanceStore.getDistinctApplicationsCount(30),
            this.clientInstanceStore.getDistinctApplicationsCount(),
        ]);
        return {
            '7d': t7d,
            '30d': t30d,
            allTime,
        };
    }
    getAppCountSnapshot(range) {
        return this.appCount?.[range];
    }
    async getSignedStats() {
        const instanceStats = await this.getStats();
        const totalProjects = instanceStats.projects
            .map((p) => p.count)
            .reduce((a, b) => a + b, 0);
        const sum = (0, js_sha256_1.sha256)(`${instanceStats.instanceId}${instanceStats.users}${instanceStats.featureToggles}${totalProjects}${instanceStats.roles}${instanceStats.groups}${instanceStats.environments}${instanceStats.segments}`);
        return { ...instanceStats, sum, projects: totalProjects };
    }
}
exports.InstanceStatsService = InstanceStatsService;
//# sourceMappingURL=instance-stats-service.js.map