"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.getXSRFToken = getXSRFToken;
exports.getVersions = getVersions;
exports.getClusterInfo = getClusterInfo;
const axios_1 = __importDefault(require("axios"));
const map_1 = __importDefault(require("lodash/map"));
const toString_1 = __importDefault(require("lodash/toString"));
const compact_1 = __importDefault(require("lodash/compact"));
const os = __importStar(require("os"));
const requestsSetup_1 = require("./requestsSetup");
const REQUEST_TIMEOUT = 15000;
function getExtra(error) {
    const { headers } = error?.request?._options || {};
    if (headers) {
        const correlationId = headers['X-YT-Correlation-Id'];
        return correlationId && { 'X-YT-Correlation-Id': correlationId };
    }
    return undefined;
}
async function getXSRFToken(req, config, actionPrefix = '') {
    const timeStart = Date.now();
    const { setup, proxyBaseUrl, authHeaders } = config;
    const xYTCorrelationId = `${req.id}.getXSRFToken`;
    function sendStats(responseStatus) {
        const timestamp = Date.now();
        req.ctx.log('getXSRFToken', {
            xYTCorrelationId,
            responseStatus,
        });
        req.ctx.stats?.('ytRequests', {
            responseStatus,
            headerContentLength: 0,
            timestamp,
            host: os.hostname(),
            service: setup.id,
            requestTime: timestamp - timeStart,
            requestId: req.id,
            action: `${actionPrefix}.getXSRFToken`,
            referer: req?.headers?.referer || '',
            page: '',
        });
    }
    return axios_1.default
        .request({
        url: proxyBaseUrl + '/auth/whoami',
        method: 'GET',
        headers: {
            ...authHeaders,
            'X-YT-Correlation-Id': xYTCorrelationId,
        },
        timeout: REQUEST_TIMEOUT,
    })
        .then((response) => {
        sendStats(response.status);
        return response.data;
    })
        .catch((e) => {
        sendStats(e?.response?.status ?? 500);
        return Promise.reject(e);
    });
}
async function getVersion({ proxyBaseUrl }) {
    return axios_1.default
        .request({
        url: proxyBaseUrl + '/version',
        method: 'GET',
        timeout: 5000,
        responseType: 'text',
    })
        .then((response) => response.data);
}
function parseVersion(version) {
    const match = version && version.match(/(\d+)\.(\d+)\.(\d+)/);
    return match && match[0];
}
function getVersions(req, clusters) {
    return Promise.all((0, map_1.default)(clusters, (clusterConfig) => {
        const { id } = clusterConfig;
        return getVersion((0, requestsSetup_1.getYTApiClusterSetup)(id))
            .then((version) => ({ id, version: parseVersion(version) }))
            .catch((error) => {
            req.ctx.logError('getVersion error', error, getExtra(error));
            return { id };
        });
    }));
}
function prepareError(message, err) {
    let error;
    let http_status_code;
    try {
        if (err?.isAxiosError) {
            error = err.response?.data;
            http_status_code = err.response?.status;
        }
        else {
            error = err;
        }
    }
    catch {
        error = err;
    }
    return {
        message: `${message}:${(0, toString_1.default)(err)}`,
        code: http_status_code,
        inner_errors: (0, compact_1.default)([error]),
    };
}
async function getClusterInfo(req, cluster) {
    const config = (0, requestsSetup_1.getUserYTApiSetup)(cluster, req);
    let tokenError, versionError;
    let token, version;
    const [tokenResult, versionResult] = await Promise.allSettled([
        getXSRFToken(req, config, 'ui_clusterInfo'),
        getVersion(config),
    ]);
    if (versionResult.status === 'fulfilled') {
        version = versionResult.value;
    }
    else {
        const err = versionResult.reason;
        versionError = prepareError('Failed to get cluster version ', err);
        req.ctx.logError('Failed to get cluster version: ' + err.toString(), err, getExtra(err));
    }
    if (tokenResult.status === 'fulfilled') {
        token = tokenResult.value;
    }
    else {
        const err = tokenResult.reason;
        tokenError = prepareError('Failed to get XSRF token ', err);
        req.ctx.logError('Failed to get XSRF token', err, getExtra(err));
    }
    return {
        token,
        version,
        tokenError,
        versionError,
    };
}
