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/CloudResource";
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 CloudResourceLabelRuleEngineService from "./CloudResourceLabelRuleEngineService";
import CloudResourceOwnerRuleEngineService from "./CloudResourceOwnerRuleEngineService";
const LAST_SEEN_CACHE_NAMESPACE = "cloud-resource-last-seen";
const LAST_SEEN_THROTTLE_SECONDS = 60;
const LABELS_APPLIED_CACHE_NAMESPACE = "cloud-resource-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 CloudResourceLabelRuleEngineService.applyRulesToCloudResource(createdItem);
            })
                .then(async () => {
                await CloudResourceOwnerRuleEngineService.applyRulesToCloudResource(createdItem);
            })
                .catch((error) => {
                var _a, _b;
                logger.error(`Error applying cloud resource rules in CloudResourceService.onCreateSuccess: ${error}`, {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    cloudResourceId: (_b = createdItem.id) === null || _b === void 0 ? void 0 : _b.toString(),
                });
            });
        }
        return createdItem;
    }
    async findOrCreateByResourceIdentifier(data) {
        const existingResource = await this.findOneBy({
            query: {
                projectId: data.projectId,
                resourceIdentifier: QueryHelper.findWithSameText(data.resourceIdentifier),
            },
            select: {
                _id: true,
                projectId: true,
                resourceIdentifier: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (existingResource) {
            return existingResource;
        }
        try {
            const newResource = new Model();
            newResource.projectId = data.projectId;
            newResource.name = data.name || data.resourceIdentifier;
            newResource.resourceIdentifier = data.resourceIdentifier;
            newResource.otelCollectorStatus = "connected";
            newResource.lastSeenAt = OneUptimeDate.getCurrentDate();
            if (data.cloudPlatform) {
                newResource.cloudPlatform = data.cloudPlatform;
            }
            if (data.cloudProvider) {
                newResource.cloudProvider = data.cloudProvider;
            }
            if (data.cloudRegion) {
                newResource.cloudRegion = data.cloudRegion;
            }
            if (data.cloudAccountId) {
                newResource.cloudAccountId = data.cloudAccountId;
            }
            const createdResource = await this.create({
                data: newResource,
                props: {
                    isRoot: true,
                },
            });
            return createdResource;
        }
        catch (_a) {
            const reFetchedResource = await this.findOneBy({
                query: {
                    projectId: data.projectId,
                    resourceIdentifier: QueryHelper.findWithSameText(data.resourceIdentifier),
                },
                select: {
                    _id: true,
                    projectId: true,
                    resourceIdentifier: true,
                },
                props: {
                    isRoot: true,
                },
            });
            if (reFetchedResource) {
                return reFetchedResource;
            }
            throw new Error("Failed to create or find cloud resource: " + data.resourceIdentifier);
        }
    }
    async updateLastSeen(cloudResourceId, extra) {
        var _a, _b, _c, _d, _e, _f, _g;
        const cacheKey = cloudResourceId.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,
            cloudPlatform: (_b = extra === null || extra === void 0 ? void 0 : extra.cloudPlatform) !== null && _b !== void 0 ? _b : null,
            cloudProvider: (_c = extra === null || extra === void 0 ? void 0 : extra.cloudProvider) !== null && _c !== void 0 ? _c : null,
            cloudRegion: (_d = extra === null || extra === void 0 ? void 0 : extra.cloudRegion) !== null && _d !== void 0 ? _d : null,
            cloudAccountId: (_e = extra === null || extra === void 0 ? void 0 : extra.cloudAccountId) !== null && _e !== void 0 ? _e : null,
            runtimeName: (_f = extra === null || extra === void 0 ? void 0 : extra.runtimeName) !== null && _f !== void 0 ? _f : null,
            runtimeVersion: (_g = extra === null || extra === void 0 ? void 0 : extra.runtimeVersion) !== null && _g !== void 0 ? _g : 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.cloudPlatform) {
            data.cloudPlatform = extra.cloudPlatform;
        }
        if (extra === null || extra === void 0 ? void 0 : extra.cloudProvider) {
            data.cloudProvider = extra.cloudProvider;
        }
        if (extra === null || extra === void 0 ? void 0 : extra.cloudRegion) {
            data.cloudRegion = extra.cloudRegion;
        }
        if (extra === null || extra === void 0 ? void 0 : extra.cloudAccountId) {
            data.cloudAccountId = extra.cloudAccountId;
        }
        if (extra === null || extra === void 0 ? void 0 : extra.runtimeName) {
            data.runtimeName = extra.runtimeName;
        }
        if (extra === null || extra === void 0 ? void 0 : extra.runtimeVersion) {
            data.runtimeVersion = extra.runtimeVersion;
        }
        await this.updateOneById({
            id: cloudResourceId,
            data: data,
            props: {
                isRoot: true,
            },
        });
    }
    async attachLabels(data) {
        var _a;
        if (!data.labelIds || data.labelIds.length === 0) {
            return;
        }
        const cacheKey = data.cloudResourceId.toString();
        const fingerprint = fingerprintLabelIds(data.labelIds);
        const cached = await GlobalCache.getString(LABELS_APPLIED_CACHE_NAMESPACE, cacheKey);
        if (cached === fingerprint) {
            return;
        }
        try {
            const resourceIdStr = data.cloudResourceId.toString();
            const existingLabels = await this.getRepository()
                .createQueryBuilder()
                .relation(Model, "labels")
                .of(resourceIdStr)
                .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(resourceIdStr)
                    .add(toAddIds);
            }
            await GlobalCache.setString(LABELS_APPLIED_CACHE_NAMESPACE, cacheKey, fingerprint, { expiresInSeconds: LABELS_APPLIED_CACHE_TTL_SECONDS });
        }
        catch (err) {
            logger.warn(`CloudResourceService.attachLabels failed for resource ${data.cloudResourceId.toString()}: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
    async markDisconnectedResources() {
        const fiveMinutesAgo = OneUptimeDate.addRemoveMinutes(OneUptimeDate.getCurrentDate(), -5);
        const connectedResources = await this.findBy({
            query: {
                otelCollectorStatus: "connected",
                lastSeenAt: QueryHelper.lessThan(fiveMinutesAgo),
            },
            select: {
                _id: true,
            },
            limit: LIMIT_MAX,
            skip: 0,
            props: {
                isRoot: true,
            },
        });
        for (const cloudResource of connectedResources) {
            if (cloudResource._id) {
                await this.updateOneById({
                    id: new ObjectID(cloudResource._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, "findOrCreateByResourceIdentifier", 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, "markDisconnectedResources", 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=CloudResourceService.js.map