var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import DatabaseService from "./DatabaseService";
import Model from "../../Models/DatabaseModels/RumApplication";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import ObjectID from "../../Types/ObjectID";
import QueryHelper from "../Types/Database/QueryHelper";
import OneUptimeDate from "../../Types/Date";
import LIMIT_MAX from "../../Types/Database/LimitMax";
import GlobalCache from "../Infrastructure/GlobalCache";
import logger from "../Utils/Logger";
import crypto from "crypto";
import RumApplicationLabelRuleEngineService from "./RumApplicationLabelRuleEngineService";
import RumApplicationOwnerRuleEngineService from "./RumApplicationOwnerRuleEngineService";
const LAST_SEEN_CACHE_NAMESPACE = "rum-application-last-seen";
const LAST_SEEN_THROTTLE_SECONDS = 60;
const LABELS_APPLIED_CACHE_NAMESPACE = "rum-application-labels-applied";
const LABELS_APPLIED_CACHE_TTL_SECONDS = 60;
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onCreateSuccess(_onCreate, createdItem) {
        if (createdItem.projectId && createdItem.id) {
            Promise.resolve()
                .then(async () => {
                await RumApplicationLabelRuleEngineService.applyRulesToRumApplication(createdItem);
            })
                .then(async () => {
                await RumApplicationOwnerRuleEngineService.applyRulesToRumApplication(createdItem);
            })
                .catch((error) => {
                var _a, _b;
                logger.error(`Error applying RUM application rules in RumApplicationService.onCreateSuccess: ${error}`, {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    rumApplicationId: (_b = createdItem.id) === null || _b === void 0 ? void 0 : _b.toString(),
                });
            });
        }
        return createdItem;
    }
    async findOrCreateByAppIdentifier(data) {
        const existingApp = await this.findOneBy({
            query: {
                projectId: data.projectId,
                appIdentifier: QueryHelper.findWithSameText(data.appIdentifier),
            },
            select: {
                _id: true,
                projectId: true,
                appIdentifier: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (existingApp) {
            return existingApp;
        }
        try {
            const newApp = new Model();
            newApp.projectId = data.projectId;
            newApp.name = data.appIdentifier;
            newApp.appIdentifier = data.appIdentifier;
            newApp.otelCollectorStatus = "connected";
            newApp.lastSeenAt = OneUptimeDate.getCurrentDate();
            const createdApp = await this.create({
                data: newApp,
                props: {
                    isRoot: true,
                },
            });
            return createdApp;
        }
        catch (_a) {
            const reFetchedApp = await this.findOneBy({
                query: {
                    projectId: data.projectId,
                    appIdentifier: QueryHelper.findWithSameText(data.appIdentifier),
                },
                select: {
                    _id: true,
                    projectId: true,
                    appIdentifier: true,
                },
                props: {
                    isRoot: true,
                },
            });
            if (reFetchedApp) {
                return reFetchedApp;
            }
            throw new Error("Failed to create or find RUM application: " + data.appIdentifier);
        }
    }
    async updateLastSeen(rumApplicationId, extra) {
        var _a, _b, _c;
        const cacheKey = rumApplicationId.toString();
        const extrasFingerprint = crypto
            .createHash("sha1")
            .update(JSON.stringify({
            agentVersion: (_a = extra === null || extra === void 0 ? void 0 : extra.agentVersion) !== null && _a !== void 0 ? _a : null,
            clientType: (_b = extra === null || extra === void 0 ? void 0 : extra.clientType) !== null && _b !== void 0 ? _b : null,
            sdkLanguage: (_c = extra === null || extra === void 0 ? void 0 : extra.sdkLanguage) !== null && _c !== void 0 ? _c : null,
        }))
            .digest("hex");
        const cached = await GlobalCache.getString(LAST_SEEN_CACHE_NAMESPACE, cacheKey);
        if (cached === extrasFingerprint) {
            return; // same data was written recently
        }
        await GlobalCache.setString(LAST_SEEN_CACHE_NAMESPACE, cacheKey, extrasFingerprint, { expiresInSeconds: LAST_SEEN_THROTTLE_SECONDS });
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const data = {
            lastSeenAt: OneUptimeDate.getCurrentDate(),
            otelCollectorStatus: "connected",
        };
        if (extra === null || extra === void 0 ? void 0 : extra.agentVersion) {
            data.agentVersion = extra.agentVersion;
        }
        if (extra === null || extra === void 0 ? void 0 : extra.clientType) {
            data.clientType = extra.clientType;
        }
        if (extra === null || extra === void 0 ? void 0 : extra.sdkLanguage) {
            data.sdkLanguage = extra.sdkLanguage;
        }
        await this.updateOneById({
            id: rumApplicationId,
            data: data,
            props: {
                isRoot: true,
            },
        });
    }
    async attachLabels(data) {
        var _a;
        if (!data.labelIds || data.labelIds.length === 0) {
            return;
        }
        const cacheKey = data.rumApplicationId.toString();
        const fingerprint = fingerprintLabelIds(data.labelIds);
        const cached = await GlobalCache.getString(LABELS_APPLIED_CACHE_NAMESPACE, cacheKey);
        if (cached === fingerprint) {
            return;
        }
        try {
            const appIdStr = data.rumApplicationId.toString();
            const existingLabels = await this.getRepository()
                .createQueryBuilder()
                .relation(Model, "labels")
                .of(appIdStr)
                .loadMany();
            const existingIds = new Set();
            for (const lbl of existingLabels) {
                const idStr = (_a = lbl._id) === null || _a === void 0 ? void 0 : _a.toString();
                if (idStr) {
                    existingIds.add(idStr);
                }
            }
            const toAddIds = [];
            const seen = new Set();
            for (const id of data.labelIds) {
                const idStr = id.toString();
                if (existingIds.has(idStr) || seen.has(idStr)) {
                    continue;
                }
                seen.add(idStr);
                toAddIds.push(idStr);
            }
            if (toAddIds.length > 0) {
                await this.getRepository()
                    .createQueryBuilder()
                    .relation(Model, "labels")
                    .of(appIdStr)
                    .add(toAddIds);
            }
            await GlobalCache.setString(LABELS_APPLIED_CACHE_NAMESPACE, cacheKey, fingerprint, { expiresInSeconds: LABELS_APPLIED_CACHE_TTL_SECONDS });
        }
        catch (err) {
            logger.warn(`RumApplicationService.attachLabels failed for application ${data.rumApplicationId.toString()}: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
    async markDisconnectedApplications() {
        const fiveMinutesAgo = OneUptimeDate.addRemoveMinutes(OneUptimeDate.getCurrentDate(), -5);
        const connectedApps = await this.findBy({
            query: {
                otelCollectorStatus: "connected",
                lastSeenAt: QueryHelper.lessThan(fiveMinutesAgo),
            },
            select: {
                _id: true,
            },
            limit: LIMIT_MAX,
            skip: 0,
            props: {
                isRoot: true,
            },
        });
        for (const rumApplication of connectedApps) {
            if (rumApplication._id) {
                await this.updateOneById({
                    id: new ObjectID(rumApplication._id.toString()),
                    data: {
                        otelCollectorStatus: "disconnected",
                    },
                    props: {
                        isRoot: true,
                    },
                });
            }
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Model]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onCreateSuccess", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "findOrCreateByAppIdentifier", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID, Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "updateLastSeen", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "attachLabels", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], Service.prototype, "markDisconnectedApplications", null);
function fingerprintLabelIds(labelIds) {
    const sorted = labelIds
        .map((id) => {
        return id.toString();
    })
        .sort();
    return crypto.createHash("sha1").update(sorted.join(",")).digest("hex");
}
export default new Service();
//# sourceMappingURL=RumApplicationService.js.map