"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.prometheusDiscoverValues = prometheusDiscoverValues;
const axios_1 = __importStar(require("axios"));
const uniqWith_1 = __importDefault(require("lodash/uniqWith"));
const isEqual_1 = __importDefault(require("lodash/isEqual"));
const utils_1 = require("../../../shared/prometheus/utils");
const utils_2 = require("../../utils");
const prometheus_utils_1 = require("./prometheus.utils");
const requestsSetup_1 = require("../../components/requestsSetup");
async function prometheusDiscoverValues(req, res) {
    const BASE_URL = req.ctx.config.prometheusBaseUrl;
    try {
        const { ytAuthCluster } = req.params;
        const { dashboardType, params: rawParmas = {} } = req.body;
        const { templating, chartParams } = await (0, prometheus_utils_1.fetchDashboardDetails)(req, {
            cluster: ytAuthCluster,
            dashboardType,
            params: rawParmas,
        });
        const results = await req.ctx.call('Fetch prometheus label values', () => {
            const queries = getDiscoverValuesParams(templating.list, chartParams, NaN);
            return Promise.all([
                ...queries.map((item) => {
                    const { label, expr } = item;
                    const key = (0, utils_1.makeDiscoverValuesKey)(item.item);
                    return axios_1.default
                        .get(`${BASE_URL}/api/v1/label/${encodeURIComponent(label)}/values?match[]=${encodeURIComponent(expr)}`, { headers: (0, requestsSetup_1.getPrometheusAuthHeaders)(ytAuthCluster) })
                        .then(({ data }) => {
                        return { key, expr, result: data };
                    })
                        .catch((e) => {
                        return {
                            key,
                            expr,
                            result: {
                                status: 'error',
                                error: (0, axios_1.isAxiosError)(e) ? e.response?.data : e,
                            },
                        };
                    });
                }),
            ]).finally(() => {
                res.appendHeader('X-UI-Prometheus-Params', queries.map((item) => JSON.stringify(item)));
            });
        });
        res.send({ results });
    }
    catch (e) {
        (0, utils_2.sendAndLogError)(req.ctx, res, null, e);
    }
}
function getDiscoverValuesParams(list, chartParams, step) {
    const toDiscover = (0, uniqWith_1.default)(list.reduce((acc, { discover_values }) => {
        if (discover_values) {
            acc.push(discover_values);
        }
        return acc;
    }, []), isEqual_1.default);
    return toDiscover.map((item) => {
        const { label, match } = item;
        const expr = (0, utils_1.replaceExprParams)(`${match}`, chartParams, step);
        return { label, item, step, expr };
    });
}
