"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.strawberryProxyApi = strawberryProxyApi;
const axios_1 = __importDefault(require("axios"));
const utils_1 = require("../utils");
const requestsSetup_1 = require("../components/requestsSetup");
const cluster_params_1 = require("../components/cluster-params");
async function strawberryProxyApi(req, res) {
    try {
        await strawberryProxyApiImpl(req, res);
    }
    catch (e) {
        await (0, utils_1.sendAndLogError)(req.ctx, res, 500, e, {
            method: 'nodejs',
            query: req.query,
            page: req.headers.referer,
        });
    }
}
const getBaseUrlConfigParameter = (engine) => {
    const CLUSTER_CONFIG_ENGINE_URL_MAP = {
        chyt: 'chyt_controller_base_url',
        spyt: 'livy_controller_base_url',
    };
    if (!(engine in CLUSTER_CONFIG_ENGINE_URL_MAP))
        return null;
    return CLUSTER_CONFIG_ENGINE_URL_MAP[engine];
};
async function strawberryProxyApiImpl(req, res) {
    const { action, engine, ytAuthCluster: cluster } = req.params;
    const ALLOWED_ACTIONS = new Set([
        'list',
        'create',
        'remove',
        'start',
        'stop',
        'get_brief_info',
        'describe_options',
        'edit_options',
        'get_speclet',
    ]);
    const baseUrlConfigParameter = getBaseUrlConfigParameter(engine);
    if (!baseUrlConfigParameter) {
        return (0, utils_1.sendAndLogError)(req.ctx, res, 400, new Error('api engine is not supported'));
    }
    if (!ALLOWED_ACTIONS.has(action)) {
        return (0, utils_1.sendAndLogError)(req.ctx, res, 400, new Error(`${engine.toUpperCase()} action - '${action}', is not supported`));
    }
    const isDeveloper = req.query.isDeveloper === 'true';
    const config = await (0, cluster_params_1.getPreloadedClusterUiConfig)(cluster, req.ctx, isDeveloper);
    const baseUrl = config[baseUrlConfigParameter];
    if (!baseUrl) {
        return (0, utils_1.sendAndLogError)(req.ctx, res, 500, new Error(`//sys/@ui_config/${baseUrlConfigParameter} is not defined`));
    }
    const { ctx } = req;
    const { authHeaders } = (0, requestsSetup_1.getUserYTApiSetup)(cluster, req);
    const headers = {
        ...ctx.getMetadata(),
        'accept-encoding': 'gzip',
        ...authHeaders,
        accept: 'application/json',
    };
    return axios_1.default
        .request({
        url: `${baseUrl}/${cluster}/${action}`,
        method: 'POST',
        headers,
        data: req.body,
        timeout: 100000,
        responseType: 'stream',
    })
        .then(async (response) => {
        const pipedSize = await (0, utils_1.pipeAxiosResponse)(ctx, res, response);
        if (!pipedSize) {
            throw new Error(utils_1.UNEXPECTED_PIPE_AXIOS_RESPONSE);
        }
    });
}
