"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const make_fetch_happen_1 = __importDefault(require("make-fetch-happen"));
const version_1 = __importDefault(require("../util/version"));
const types_1 = require("../types");
const util_1 = require("../util");
class VersionService {
    constructor({ settingStore, strategyStore, userStore, featureToggleStore, projectStore, environmentStore, contextFieldStore, groupStore, roleStore, segmentStore, eventStore, featureStrategiesStore, }, { getLogger, versionCheck, enterpriseVersion, telemetry, }, getActiveUsers, getProductionChanges) {
        this.logger = getLogger('lib/services/version-service.js');
        this.settingStore = settingStore;
        this.strategyStore = strategyStore;
        this.userStore = userStore;
        this.featureToggleStore = featureToggleStore;
        this.projectStore = projectStore;
        this.environmentStore = environmentStore;
        this.contextFieldStore = contextFieldStore;
        this.groupStore = groupStore;
        this.roleStore = roleStore;
        this.segmentStore = segmentStore;
        this.eventStore = eventStore;
        this.getActiveUsers = getActiveUsers;
        this.getProductionChanges = getProductionChanges;
        this.featureStrategiesStore = featureStrategiesStore;
        this.current = {
            oss: version_1.default,
            enterprise: enterpriseVersion || '',
        };
        this.enabled = versionCheck.enable || false;
        this.telemetryEnabled = telemetry;
        this.versionCheckUrl = versionCheck.url;
        this.isLatest = true;
    }
    async readInstanceId() {
        try {
            const { id } = (await this.settingStore.get('instanceInfo')) ?? { id: undefined };
            return id;
        }
        catch (err) {
            this.logger.warn('Could not find instanceInfo', err);
        }
    }
    async getInstanceId() {
        if (!this.instanceId) {
            this.instanceId = await this.readInstanceId();
        }
        return this.instanceId;
    }
    async checkLatestVersion() {
        const instanceId = await this.getInstanceId();
        this.logger.debug(`Checking for newest version for instanceId=${instanceId}`);
        if (this.enabled) {
            try {
                const versionPayload = {
                    versions: this.current,
                    instanceId: instanceId,
                };
                if (this.telemetryEnabled) {
                    versionPayload.featureInfo =
                        await this.getFeatureUsageInfo();
                }
                if (this.versionCheckUrl) {
                    const res = await (0, make_fetch_happen_1.default)(this.versionCheckUrl, {
                        method: 'POST',
                        body: JSON.stringify(versionPayload),
                        headers: { 'Content-Type': 'application/json' },
                    });
                    if (res.ok) {
                        const data = (await res.json());
                        this.latest = {
                            oss: data.versions.oss,
                            enterprise: data.versions.enterprise,
                        };
                        this.isLatest = data.latest;
                    }
                    else {
                        this.logger.info(`Could not check newest version. Status: ${res.status}`);
                    }
                }
                else {
                    this.logger.info('Had no URL to check newest version');
                }
            }
            catch (err) {
                this.logger.info('Could not check newest version', err);
            }
        }
    }
    async getFeatureUsageInfo() {
        const [featureToggles, users, projects, contextFields, groups, roles, customRootRoles, customRootRolesInUse, environments, segments, strategies, SAMLenabled, OIDCenabled, featureExports, featureImports, userActive, productionChanges,] = await Promise.all([
            this.featureToggleStore.count({
                archived: false,
            }),
            this.userStore.count(),
            this.projectStore.count(),
            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.eventStore.filteredCount({ type: types_1.FEATURES_EXPORTED }),
            this.eventStore.filteredCount({ type: types_1.FEATURES_IMPORTED }),
            this.userStats(),
            this.productionChanges(),
        ]);
        const versionInfo = await this.getVersionInfo();
        const customStrategies = await this.strategyStore.getEditableStrategies();
        const customStrategiesInUse = await this.featureStrategiesStore.getCustomStrategiesInUseCount();
        const featureInfo = {
            featureToggles,
            users,
            projects,
            contextFields,
            groups,
            roles,
            customRootRoles,
            customRootRolesInUse,
            environments,
            segments,
            strategies,
            SAMLenabled,
            OIDCenabled,
            featureExports,
            featureImports,
            customStrategies: customStrategies.length,
            customStrategiesInUse: customStrategiesInUse,
            instanceId: versionInfo.instanceId,
            versionOSS: versionInfo.current.oss,
            versionEnterprise: versionInfo.current.enterprise,
            activeUsers30: userActive.last30,
            activeUsers60: userActive.last60,
            activeUsers90: userActive.last90,
            productionChanges30: productionChanges.last30,
            productionChanges60: productionChanges.last60,
            productionChanges90: productionChanges.last90,
        };
        return featureInfo;
    }
    async userStats() {
        const { last30, last60, last90 } = await this.getActiveUsers();
        return { last30, last60, last90 };
    }
    async productionChanges() {
        return this.getProductionChanges();
    }
    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;
    }
    async getVersionInfo() {
        const instanceId = await this.getInstanceId();
        return {
            current: this.current,
            latest: this.latest || {},
            isLatest: this.isLatest,
            instanceId: instanceId || 'unresolved-instance-id',
        };
    }
}
exports.default = VersionService;
//# sourceMappingURL=version-service.js.map