"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.odinProxyApi = odinProxyApi;
const isEmpty_1 = __importDefault(require("lodash/isEmpty"));
const has_1 = __importDefault(require("lodash/has"));
const axios_1 = __importDefault(require("axios"));
const qs_1 = __importDefault(require("qs"));
const utils_1 = require("../utils");
async function odinProxyApi(req, res) {
    try {
        await odinProxyApiImpl(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 odinProxyApiImpl(req, res) {
    const { action, ytAuthCluster: cluster } = req.params;
    const { odinBaseUrl } = req.ctx.config;
    const odinPath = typeof odinBaseUrl === 'string' ? odinBaseUrl : odinBaseUrl?.[cluster];
    if (!odinPath) {
        return (0, utils_1.sendAndLogError)(req.ctx, res, 500, new Error('Odin base url is not configured'));
    }
    const { ctx, query } = req;
    const search = (0, isEmpty_1.default)(query) ? '' : `?${qs_1.default.stringify(query)}`;
    const allowedActionsUrls = {
        service_list: `${odinPath}/service_list`,
        exists: `${odinPath}/${action}/${cluster}`,
        availability: `${odinPath}/${action}/${cluster}${search}`,
    };
    if (!(0, has_1.default)(allowedActionsUrls, action)) {
        return (0, utils_1.sendAndLogError)(req.ctx, res, 400, new Error(`Odin action - ${action}, is not supported`));
    }
    const url = allowedActionsUrls[action];
    return axios_1.default
        .request({
        url,
        method: req.method,
        headers: { ...ctx.getMetadata(), '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);
        }
    });
}
