"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ytTvmApiHandler = ytTvmApiHandler;
const axios_1 = __importDefault(require("axios"));
const qs_1 = __importDefault(require("qs"));
const isEmpty_1 = __importDefault(require("lodash/isEmpty"));
// @ts-ignore
const javascript_wrapper_1 = __importDefault(require("@ytsaurus/javascript-wrapper"));
const utils_1 = require("../utils");
const os = __importStar(require("os"));
const utils_2 = require("../../shared/utils");
const constants_1 = require("../../shared/constants");
const requestsSetup_1 = require("../components/requestsSetup");
const yt = (0, javascript_wrapper_1.default)();
const YT_API_REQUEST_ID_HEADER_LOWER = constants_1.YT_API_REQUEST_ID_HEADER.toLowerCase();
const YT_KNOWN_COMMANDS = new Set(['get_job_stderr', 'get_job_input', 'get_job_fail_context']);
const supportedCommands = yt.getSupportedCommands();
async function ytTvmApiHandler(req, res) {
    const { ctx, params } = req;
    const { referer } = req.headers;
    async function sendError(e, statusCode = null) {
        await (0, utils_1.sendAndLogError)(ctx, res, statusCode, e, {
            method: 'nodejs',
            query: req.query,
            page: referer,
        });
    }
    let cfg;
    try {
        cfg = (0, requestsSetup_1.getUserYTApiSetup)(params.ytAuthCluster, req);
    }
    catch (e) {
        return sendError(e, 400);
    }
    const { setup, authHeaders, isLocalCluster } = cfg;
    const { [params.version]: clusterApi } = supportedCommands;
    if (!clusterApi) {
        return sendError(new Error(`Unexpected api version: [${params.version}]`), 400);
    }
    const commandInfo = clusterApi.get(params.command);
    if (!commandInfo && !YT_KNOWN_COMMANDS.has(params.command)) {
        return sendError(new Error(`Unexpected command: [${params.command}]`), 400);
    }
    const action = `${params.version}/${params.command}`;
    const timeStart = Date.now();
    const { [YT_API_REQUEST_ID_HEADER_LOWER]: ytApiId } = req.headers;
    function sendStats(overrides) {
        const timestamp = Date.now();
        const { headerContentLength } = overrides;
        const contentLength = Number(headerContentLength);
        ctx.stats?.('ytRequests', {
            ...overrides,
            headerContentLength: isNaN(contentLength) ? 0 : contentLength,
            timestamp,
            host: os.hostname(),
            service: setup.id,
            requestTime: timestamp - timeStart,
            requestId: req.id,
            action: ytApiId || action,
            referer: referer ?? '',
            page: !referer ? '' : (0, utils_2.getYtPageIdParts)(referer).getPage(),
        });
    }
    try {
        const { proxy, secure } = setup;
        const proto = secure ? 'https' : 'http';
        let requestProxy = proxy;
        if (commandInfo?.heavy && !isLocalCluster && !setup.disableHeavyProxies) {
            ctx.log(`Request heavy proxy for command '${params.command}'`);
            const res = await axios_1.default.request({
                method: 'GET',
                url: `${proto}://${proxy}/hosts`,
                headers: ctx.getMetadata(),
            });
            requestProxy = res.data[0];
        }
        const search = (0, isEmpty_1.default)(req.query) ? '' : `?${qs_1.default.stringify(req.query)}`;
        const requestUrl = `${proto}://${requestProxy}/api/${action}${search}`;
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const { host, cookie, [YT_API_REQUEST_ID_HEADER_LOWER]: _apiId, ...rest } = req.headers;
        ctx.log('Request', { requestUrl, 'X-YT-Correlation-Id': req.id });
        await axios_1.default
            .request({
            url: requestUrl,
            method: req.method,
            headers: {
                ...ctx.getMetadata(),
                ...rest,
                'accept-encoding': 'gzip',
                'X-YT-Correlation-Id': req.id,
                'X-YT-Suppress-Redirect': '1',
                ...authHeaders,
            },
            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);
            }
            sendStats({ ...pipedSize, responseStatus: response.status });
        });
    }
    catch (e) {
        try {
            await sendError(e, 500);
        }
        catch { }
        sendStats({
            responseStatus: e?.response?.status || 500,
        });
    }
}
