const _ = require('lodash');
const fetch = require('node-fetch');
const querystring = require('querystring');
const blackbox = require('../util/common/blackbox');
const log = require('../util/common/log');
const config = require('../config');

const DBFIELDS = [
    'userinfo.lang.uid',
    'userinfo.country.uid'
];

module.exports = (req, res, next) => {
    let headers = {
        'x-request-id': req.get('x-request-id')
    };

    // https://doc.yandex-team.ru/blackbox/reference/MethodSessionID.html
    let query = Object.assign(blackbox.getContextOptions(req), {
        method: 'sessionid',
        emails: 'getall',
        regname: 'yes',
        multisession: 'yes',
        dbfields: DBFIELDS.join(','),
        format: 'json'
    });

    let tvmServiceTicket = _.get(req.context, 'tvm_tickets.blackbox');

    if (tvmServiceTicket) {
        headers['X-Ya-Service-Ticket'] = tvmServiceTicket;
        query.get_user_ticket = 'yes';
    }

    let url = config.api.blackbox + '?' + querystring.stringify(query);
    let options = { method: 'get', headers };

    return blackbox.verifyInput(url, options)
        .then(() => log(fetch)(url, options))
        .then(response => response.json())
        .then(blackbox.verifyOutput)
        .then(blackbox.preprocessOutput)
        .then(data => {
            let nextHeaders = {
                'x-uid': data.default_uid
            };

            if (data.user_ticket) {
                nextHeaders['X-Ya-User-Ticket'] = data.user_ticket;
                nextHeaders['X-Ya-Service-Ticket'] = _.get(req.context, 'tvm_tickets.directory_admin');
            }
            else nextHeaders['Authorization'] = `Token ${config.tokens.directory}`;

            _.merge(req.context, { session: data, headers: nextHeaders });
            next();
        })
        .catch(data => {
            log('@error Authorization failed', data);
            _.merge(req.context, { session: data });
            next();
        });
};
