"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.prometheusQueryRange = prometheusQueryRange;
const axios_1 = __importDefault(require("axios"));
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 prometheusQueryRange(req, res) {
    const BASE_URL = req.ctx.config.prometheusBaseUrl;
    try {
        const { ytAuthCluster } = req.params;
        const { id } = req.query;
        const { dashboardType, start, end, step, params: rawParmas } = req.body;
        const { panel, chartParams } = await (0, prometheus_utils_1.fetchDashboardDetails)(req, {
            cluster: ytAuthCluster,
            dashboardType,
            params: rawParmas,
            chartId: id,
        });
        const { targets } = panel ?? {};
        const results = await req.ctx.call('Fetch prometheus data', () => {
            const queries = targets?.map(({ expr }) => {
                const query = (0, utils_1.replaceExprParams)(expr, chartParams, step);
                return { query, start, end, step };
            }) ?? [];
            return Promise.all(queries.map((params) => {
                return axios_1.default
                    .get(`${BASE_URL}/api/v1/query_range?`, {
                    params,
                    headers: (0, requestsSetup_1.getPrometheusAuthHeaders)(ytAuthCluster),
                })
                    .then(async (response) => {
                    return response.data;
                });
            })).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);
    }
}
