"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ytTabletErrorsApi = ytTabletErrorsApi;
const isEmpty_1 = __importDefault(require("lodash/isEmpty"));
const axios_1 = __importDefault(require("axios"));
const qs_1 = __importDefault(require("qs"));
const utils_1 = require("../utils");
const requestsSetup_1 = require("../components/requestsSetup");
const tablet_errors_manager_1 = require("../../shared/tablet-errors-manager");
const cluster_params_1 = require("../components/cluster-params");
async function ytTabletErrorsApi(req, res) {
    try {
        await ytTabletErrorsApiImpl(req, res);
    }
    catch (e) {
        await (0, utils_1.sendAndLogError)(req.ctx, res, 500, e, {
            method: 'nodejs',
            query: req.query,
            page: req.headers.referer,
        });
    }
}
function isTabletErrorsManagerPostAction(v) {
    return tablet_errors_manager_1.TABLET_ERRORS_MANAGER_POST_ACTIONS.has(v);
}
async function ytTabletErrorsApiImpl(req, res) {
    const { ctx, query } = req;
    const { action, ytAuthCluster } = req.params;
    const { tabletErrorsBaseUrl } = ctx.config;
    const isDeveloper = req.query.isDeveloper === 'true';
    const config = await (0, cluster_params_1.getPreloadedClusterUiConfig)(ytAuthCluster, req.ctx, isDeveloper);
    const clusterSpecificBaseUrl = config?.tablet_errors_base_url;
    if (!tabletErrorsBaseUrl) {
        throw new utils_1.ErrorWithCode(404, 'The installation of UI is not configured to work with TabletErrorsManager, check your config.tabletErrorsBaseUrl');
    }
    if (!isTabletErrorsManagerPostAction(action)) {
        throw new utils_1.ErrorWithCode(404, 'Unexpected action: ' + action);
    }
    const search = (0, isEmpty_1.default)(query) ? '' : `?${qs_1.default.stringify(query)}`;
    let cfg;
    try {
        cfg = (0, requestsSetup_1.getUserTabletErrorApiSetup)(ytAuthCluster, req, Boolean(clusterSpecificBaseUrl));
    }
    catch (e) {
        return (0, utils_1.sendAndLogError)(req.ctx, res, 400, e);
    }
    const { authHeaders } = cfg;
    return axios_1.default
        .request({
        url: `${clusterSpecificBaseUrl ?? tabletErrorsBaseUrl}/${action}${search}`,
        method: req.method,
        headers: { ...ctx.getMetadata(), ...authHeaders, 'accept-encoding': 'gzip' },
        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);
        }
    });
}
