// временный адаптер, воссоздающий данные в том виде,
// в каком они выходили из легаси-миддлвар для tvm и blackbox
const _get = require('lodash/get');
const _merge = require('lodash/merge');
const getUserIp = require('../lib2/getUserIp');
const isSocialAccount = require('../lib2/isSocialAccount');
const isLiteAccount = require('../lib2/isLiteAccount');
const isInternalAccount = require('../lib2/isInternalAccount');

const ValidStatuses = ['VALID', 'NEED_RESET'];

module.exports = () => (req, res, next) => {
    let { tvm, blackbox } = req;
    let output = {};

    if (!tvm || !blackbox || !ValidStatuses.includes(blackbox.status)) {
        req.context.auth = {
            errorCode: 401,
            message: blackbox && blackbox.error,
            status: blackbox && blackbox.status,
        };

        return next();
    }

    output.auth = {
        'x-user-ip': getUserIp(req),
        'x-uid': blackbox.uid,
        'X-Ya-User-Ticket': blackbox.userTicket,
        'X-Ya-Service-Ticket': _get(tvm, 'tickets.directory.ticket'),
    };

    output.tvm_tickets = Object.entries(tvm.tickets || {})
        .reduce((acc, [k, v]) => {
            acc[k.replace(/\-/g, '_')] = v.ticket;

            if (k === 'directory') {
                acc.directory_api = acc[k];
            }

            return acc;
        }, {});

    output.state = {
        session: blackbox.uid,
        reset_required: blackbox.status === 'NEED_RESET',
    };

    output.sessions = (blackbox.raw.users || [])
        .map(user => ({
            id: user.id,
            login: user.login,
            display_name: _get(user, 'display_name.name'),
            avatar_id: _get(user, 'display_name.avatar.default'),
            locale: _get(user, 'attributes.34'),
            country: _get(user, 'attributes.31'),
            org_id: _get(user, 'attributes.1017'), // comma-separated org_ids
            is_social: isSocialAccount(user),
            is_light: isLiteAccount(user),
            internal: isInternalAccount(user),
        }));

    output.session = output.sessions.find(user => user.id === blackbox.uid);
    output.karma = blackbox.karma;

    req.context = _merge(output, req.context);

    next();
};
