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 ObjectID from "../../../Types/ObjectID";
import PositiveNumber from "../../../Types/PositiveNumber";
import Search from "../../../Types/BaseDatabase/Search";
import MultiSearch from "../../../Types/BaseDatabase/MultiSearch";
import ServiceService from "../../Services/ServiceService";
import HostService from "../../Services/HostService";
import DockerHostService from "../../Services/DockerHostService";
import KubernetesClusterService from "../../Services/KubernetesClusterService";
import ServerlessFunctionService from "../../Services/ServerlessFunctionService";
import CloudResourceService from "../../Services/CloudResourceService";
import RumApplicationService from "../../Services/RumApplicationService";
import CaptureSpan from "./CaptureSpan";
/*
 * Facet keys whose values are entity IDs backed by a Postgres source-of-truth
 * table. ClickHouse aggregation only sees IDs that appear in the sampled
 * trace/log window, so low-volume resources never reach the filter sidebar.
 * Resolving the value list from Postgres instead means every project resource
 * shows up regardless of recent telemetry activity, and the sidebar search
 * matches across the full set (not just the loaded subset).
 *
 * `serviceId` is the pre-rename alias of `primaryEntityId`, kept so stale
 * clients keep resolving the Services facet across a deploy.
 */
export const RESOURCE_FACET_KEYS = new Set([
    "primaryEntityId",
    "serviceId",
    "hostId",
    "dockerHostId",
    "kubernetesClusterId",
    "serverlessFunctionId",
    "cloudResourceId",
    "rumApplicationId",
]);
class ResourceFacetResolver {
    static isResourceFacet(facetKey) {
        return RESOURCE_FACET_KEYS.has(facetKey);
    }
    static async resolve(projectId, specs) {
        const results = await Promise.all(specs.map(async (spec) => {
            try {
                const values = await ResourceFacetResolver.resolveOne(projectId, spec);
                return [spec.facetKey, values];
            }
            catch (_a) {
                return [spec.facetKey, []];
            }
        }));
        return Object.fromEntries(results);
    }
    static async resolveOne(projectId, spec) {
        var _a;
        const limit = (_a = spec.limit) !== null && _a !== void 0 ? _a : ResourceFacetResolver.DEFAULT_LIMIT;
        const searchText = spec.searchText && spec.searchText.trim().length > 0
            ? spec.searchText.trim()
            : undefined;
        switch (spec.facetKey) {
            case "primaryEntityId":
            case "serviceId":
                return ResourceFacetResolver.queryServices(projectId, spec.counts, searchText, limit);
            case "hostId":
                return ResourceFacetResolver.queryHosts(projectId, spec.counts, searchText, limit);
            case "dockerHostId":
                return ResourceFacetResolver.queryDockerHosts(projectId, spec.counts, searchText, limit);
            case "kubernetesClusterId":
                return ResourceFacetResolver.queryKubernetesClusters(projectId, spec.counts, searchText, limit);
            case "serverlessFunctionId":
                return ResourceFacetResolver.queryServerlessFunctions(projectId, spec.counts, searchText, limit);
            case "cloudResourceId":
                return ResourceFacetResolver.queryCloudResources(projectId, spec.counts, searchText, limit);
            case "rumApplicationId":
                return ResourceFacetResolver.queryRumApplications(projectId, spec.counts, searchText, limit);
            default:
                return [];
        }
    }
    static async queryServices(projectId, counts, searchText, limit) {
        const query = { projectId };
        if (searchText) {
            query["name"] = new Search(searchText);
        }
        const services = await ServiceService.findBy({
            query: query,
            select: {
                _id: true,
                name: true,
            },
            limit: new PositiveNumber(limit),
            skip: new PositiveNumber(0),
            props: { isRoot: true },
        });
        return ResourceFacetResolver.mergeCounts(services.map((s) => {
            return {
                id: s._id ? s._id.toString() : "",
                displayName: s.name || "Unknown",
            };
        }), counts);
    }
    static async queryHosts(projectId, counts, searchText, limit) {
        const query = { projectId };
        if (searchText) {
            query["name"] = new MultiSearch({
                fields: ["name", "hostIdentifier"],
                value: searchText,
            });
        }
        const hosts = await HostService.findBy({
            query: query,
            select: {
                _id: true,
                name: true,
                hostIdentifier: true,
            },
            limit: new PositiveNumber(limit),
            skip: new PositiveNumber(0),
            props: { isRoot: true },
        });
        return ResourceFacetResolver.mergeCounts(hosts.map((h) => {
            return {
                id: h._id ? h._id.toString() : "",
                displayName: h.name || h.hostIdentifier || "Unknown",
            };
        }), counts);
    }
    static async queryDockerHosts(projectId, counts, searchText, limit) {
        const query = { projectId };
        if (searchText) {
            query["name"] = new MultiSearch({
                fields: ["name", "hostIdentifier"],
                value: searchText,
            });
        }
        const dockerHosts = await DockerHostService.findBy({
            query: query,
            select: {
                _id: true,
                name: true,
                hostIdentifier: true,
            },
            limit: new PositiveNumber(limit),
            skip: new PositiveNumber(0),
            props: { isRoot: true },
        });
        return ResourceFacetResolver.mergeCounts(dockerHosts.map((d) => {
            return {
                id: d._id ? d._id.toString() : "",
                displayName: d.name || d.hostIdentifier || "Unknown",
            };
        }), counts);
    }
    static async queryKubernetesClusters(projectId, counts, searchText, limit) {
        const query = { projectId };
        if (searchText) {
            query["name"] = new MultiSearch({
                fields: ["name", "clusterIdentifier"],
                value: searchText,
            });
        }
        const clusters = await KubernetesClusterService.findBy({
            query: query,
            select: {
                _id: true,
                name: true,
                clusterIdentifier: true,
            },
            limit: new PositiveNumber(limit),
            skip: new PositiveNumber(0),
            props: { isRoot: true },
        });
        return ResourceFacetResolver.mergeCounts(clusters.map((c) => {
            return {
                id: c._id ? c._id.toString() : "",
                displayName: c.name || c.clusterIdentifier || "Unknown",
            };
        }), counts);
    }
    static async queryServerlessFunctions(projectId, counts, searchText, limit) {
        const query = { projectId };
        if (searchText) {
            query["name"] = new MultiSearch({
                fields: ["name", "functionIdentifier"],
                value: searchText,
            });
        }
        const functions = await ServerlessFunctionService.findBy({
            query: query,
            select: {
                _id: true,
                name: true,
                functionIdentifier: true,
            },
            limit: new PositiveNumber(limit),
            skip: new PositiveNumber(0),
            props: { isRoot: true },
        });
        return ResourceFacetResolver.mergeCounts(functions.map((f) => {
            return {
                id: f._id ? f._id.toString() : "",
                displayName: f.name || f.functionIdentifier || "Unknown",
            };
        }), counts);
    }
    static async queryCloudResources(projectId, counts, searchText, limit) {
        const query = { projectId };
        if (searchText) {
            query["name"] = new MultiSearch({
                fields: ["name", "resourceIdentifier"],
                value: searchText,
            });
        }
        const resources = await CloudResourceService.findBy({
            query: query,
            select: {
                _id: true,
                name: true,
                resourceIdentifier: true,
            },
            limit: new PositiveNumber(limit),
            skip: new PositiveNumber(0),
            props: { isRoot: true },
        });
        return ResourceFacetResolver.mergeCounts(resources.map((r) => {
            return {
                id: r._id ? r._id.toString() : "",
                displayName: r.name || r.resourceIdentifier || "Unknown",
            };
        }), counts);
    }
    static async queryRumApplications(projectId, counts, searchText, limit) {
        const query = { projectId };
        if (searchText) {
            query["name"] = new MultiSearch({
                fields: ["name", "appIdentifier"],
                value: searchText,
            });
        }
        const apps = await RumApplicationService.findBy({
            query: query,
            select: {
                _id: true,
                name: true,
                appIdentifier: true,
            },
            limit: new PositiveNumber(limit),
            skip: new PositiveNumber(0),
            props: { isRoot: true },
        });
        return ResourceFacetResolver.mergeCounts(apps.map((a) => {
            return {
                id: a._id ? a._id.toString() : "",
                displayName: a.name || a.appIdentifier || "Unknown",
            };
        }), counts);
    }
    /*
     * Combine Postgres-sourced entities with counts from the ClickHouse sample.
     * Entities without a count default to 0 (they exist in the project but
     * had no telemetry in the active window). Sorts active-first so the
     * highest-traffic resources surface at the top of the sidebar.
     */
    static mergeCounts(entities, counts) {
        const out = entities
            .filter((e) => {
            return e.id.length > 0;
        })
            .map((e) => {
            return {
                value: e.id,
                count: counts.get(e.id) || 0,
                displayName: e.displayName,
            };
        });
        out.sort((a, b) => {
            if (a.count !== b.count) {
                return b.count - a.count;
            }
            return a.displayName.localeCompare(b.displayName);
        });
        return out;
    }
}
ResourceFacetResolver.DEFAULT_LIMIT = 500;
export default ResourceFacetResolver;
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID,
        Array]),
    __metadata("design:returntype", Promise)
], ResourceFacetResolver, "resolve", null);
//# sourceMappingURL=ResourceFacetResolver.js.map