const { URL } = require('url');
const _get = require('lodash/get');
const expressBlackbox = require('@yandex-int/express-blackbox');
const expressBlackboxProxy = require('./expressBlackboxProxy');
const getDuration = require('../lib2/getDuration');

const BlackboxConfig = {
    method: 'sessionid',
    attributes: {
        login: '1008',
        country: '31',
        lang: '34',
        internal: '1011',
        org_ids: '1017',
    },
    aliases: '1,5,6',
    regname: 'yes',
    multisession: 'yes',
    get_user_ticket: 'yes',
};

function getServiceTicket(req) {
    let ticket = _get(req, 'tvm.tickets.blackbox.ticket');
    let error = _get(req, 'tvm.error');

    if (!ticket || error) {
        console.error(error || 'Blackbox TVM ticket error', {
            requestId: req.ctx.requestId,
        });
    }

    return ticket;
}

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

        if (req.tvm && req.tvm.proxied) {
            expressBlackboxProxy({
                proxyUrl: new URL('/portal/apiproxy/blackbox', req.config.api.tvm).href,
            })(req, res, next);
        } else {
            expressBlackbox({
                ...BlackboxConfig,
                getServiceTicket,
                api: new URL(req.config.api.blackbox).hostname,
            })(req, res, next);
        }
    },
    (req, res, next) => {
        let logOptions = {
            requestId: req.ctx.requestId,
            duration: getDuration(req.ctx.blackboxStartTime),
        };

        if (!req.blackbox || req.blackbox.error !== 'OK') {
            // eslint-disable-next-line no-console
            console.error('BlackBox error', {
                ...logOptions,
                error: req.blackbox && req.blackbox.error,
            });
        } else {
            // eslint-disable-next-line no-console
            console.log('BlackBox OK', {
                ...logOptions,
                uid: req.blackbox.uid,
                status: req.blackbox.status,
            });
        }

        delete req.ctx.blackboxStartTime;

        next();
    },
];
