"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ytProxyApi = ytProxyApi;
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");
async function ytProxyApi(req, res) {
    try {
        await ytProxyApiImpl(req, res);
    }
    catch (e) {
        await (0, utils_1.sendAndLogError)(req.ctx, res, 500, e, {
            method: 'nodejs',
            query: req.query,
            page: req.headers.referer,
        });
    }
}
const ALLOWED_ACTION = {
    ['hosts-all']: '/hosts/all',
    ['internal-discover_versions']: '/internal/discover_versions/v2',
};
async function ytProxyApiImpl(req, res) {
    const { ctx, query } = req;
    const { command, ytAuthCluster } = req.params;
    const proxyAction = ALLOWED_ACTION[command];
    if (!proxyAction) {
        throw new Error('Unexpected action ' + command);
    }
    const search = (0, isEmpty_1.default)(query) ? '' : `?${qs_1.default.stringify(query)}`;
    let cfg;
    try {
        cfg = (0, requestsSetup_1.getUserYTApiSetup)(ytAuthCluster, req);
    }
    catch (e) {
        return (0, utils_1.sendAndLogError)(req.ctx, res, 400, e);
    }
    const { authHeaders, proxyBaseUrl } = cfg;
    return axios_1.default
        .request({
        url: `${proxyBaseUrl}${proxyAction}${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);
        }
    });
}
