"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ytAccountsUsageApi = ytAccountsUsageApi;
exports.ytAccountsUsageCheckAvailable = ytAccountsUsageCheckAvailable;
const axios_1 = __importDefault(require("axios"));
const isEmpty_1 = __importDefault(require("lodash/isEmpty"));
const qs_1 = __importDefault(require("qs"));
const ServerFactory_1 = __importDefault(require("../ServerFactory"));
const utils_1 = require("../utils");
const config_utils_1 = require("../utils/config-utils");
async function ytAccountsUsageApi(req, res) {
    try {
        await ytAccountsUsageApiImpl(req, res);
    }
    catch (e) {
        await (0, utils_1.sendAndLogError)(req.ctx, res, 500, e, {
            method: 'nodejs',
            query: req.query,
            page: req.headers.referer,
        });
    }
}
async function ytAccountsUsageCheckAvailable(req, res) {
    try {
        const { baseUrl } = await getAccountsUsageBaseUrl(req);
        res.send({ is_accounts_usage_available: Boolean(baseUrl) });
    }
    catch (e) {
        await (0, utils_1.sendAndLogError)(req.ctx, res, 500, e, {
            method: 'nodejs',
            query: req.query,
            page: req.headers.referer,
        });
    }
}
function getAccountsUsageBaseUrl(req) {
    const { ytAuthCluster: cluster } = req.params;
    const isDeveloper = req.cookies.ui_config_mode === 'developer';
    return (0, config_utils_1.getBaseUrlFromConfiguration)(req, {
        cluster,
        isDeveloper,
        uiSettingsFieldName: 'accountsUsageBasePath',
    });
}
const ALLOWED_ACTIONS = new Set([
    'list-timestamps',
    'get-resource-usage',
    'get-children-and-resource-usage',
    'get-versioned-resource-usage',
    'get-resource-usage-diff',
    'get-children-and-resource-usage-diff',
]);
async function ytAccountsUsageApiImpl(req, res) {
    const { action } = req.params;
    if (!ALLOWED_ACTIONS.has(action)) {
        throw new utils_1.ErrorWithCode(404, 'Unexpected action for Accounts usage');
    }
    const { baseUrl, testing } = await getAccountsUsageBaseUrl(req);
    if (!baseUrl) {
        throw new utils_1.ErrorWithCode(404, 'The UI installation is not configured to display "Accounts/Detailed usage" tab for current cluster. Please check your configuration: config.uiSettings.accountsUsageBasePath, //sys/@ui_config/resource_usage_base_url');
    }
    const authType = testing ? 'accountsUsageTest' : 'accountsUsageProd';
    const authHeaders = ServerFactory_1.default.getAuthHeaders(authType, req);
    const search = (0, isEmpty_1.default)(req.query) ? '' : `?${qs_1.default.stringify(req.query)}`;
    return axios_1.default
        .request({
        url: `${baseUrl}/${action}${search}`,
        method: req.method,
        headers: { ...req.ctx.getMetadata(), ...authHeaders, 'accept-encoding': 'gzip' },
        data: req.body,
        timeout: 100000,
        responseType: 'stream',
    })
        .then(async (response) => {
        const pipedSize = await (0, utils_1.pipeAxiosResponse)(req.ctx, res, response);
        if (!pipedSize) {
            throw new Error(utils_1.UNEXPECTED_PIPE_AXIOS_RESPONSE);
        }
    });
}
