const { URL } = require('url');
const expressTvm = require('@yandex-int/express-tvm').default;
const expressTvmProxy = require('./expressTvmProxy');
const getEnv = require('../lib2/getEnv');
const getUserIp = require('../lib2/getUserIp');
const getDuration = require('../lib2/getDuration');

const TvmConfig = {
    destinations: [
        'directory-api',
        'blackbox',
        'gendarme',
        'dns',
        'fouras',
        'setter',
    ],
    token: process.env.TVMTOOL_LOCAL_AUTHTOKEN || process.env.QLOUD_TVM_TOKEN,
};

const TvmProxyEnvs = [
    'development',
    'ui-test',
];

module.exports = () => [
    (req, res, next) => {
        req.ctx.tvmStartTime = process.hrtime();

        // temp
        // @see express-tvm + tvmtool
        if (TvmProxyEnvs.includes(getEnv(req))) {
            expressTvmProxy({
                proxyUrl: new URL('/portal/apiproxy/tvm', req.config.api.tvm).href,
            })(req, res, next);
        } else {
            expressTvm({
                ...TvmConfig,
                serverUrl: new URL(req.config.api.tvm).origin,
            })(req, res, next);
        }
    },
    (req, res, next) => {
        let logOptions = {
            requestId: req.ctx.requestId,
            duration: getDuration(req.ctx.tvmStartTime),
        };

        if (!req.tvm || req.tvm.error) {
            // eslint-disable-next-line no-console
            console.error('TVM error', {
                ...logOptions,
                error: req.tvm && req.tvm.error,
            });
        } else {
            // eslint-disable-next-line no-console
            console.log('TVM OK', logOptions);
        }

        delete req.ctx.tvmStartTime;

        // TODO: переименовать 'directory-api' в 'directory' в окружении
        if (req.tvm && req.tvm.tickets) {
            req.tvm.tickets.directory = req.tvm.tickets['directory-api'];
        }

        if (req.tvm && !req.tvm.proxied && getEnv(req) !== 'production') {
            req.tvm.ip = getUserIp(req);
        }

        next();
    },
];
