// qloud tvm config
// https://wiki.yandex-team.ru/qloud/doc/secrets/TVM/

// qloud tvm api
// https://wiki.yandex-team.ru/passport/tvm2/qloud/

// blackbox destination ids
// https://wiki.yandex-team.ru/passport/tvm2/user-ticket/#0-opredeljaemsjasokruzhenijami

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

module.exports = fetchAllTickets;

function fetchAllTickets(req, res, next) {
    const token = process.env.TVMTOOL_LOCAL_AUTHTOKEN || process.env.QLOUD_TVM_TOKEN;
    const tvmConfig = JSON.parse(process.env.QLOUD_TVM_CONFIG);

    let clients = tvmConfig ? tvmConfig.clients : null;

    if (!token || !clients) {
        return Promise.resolve();
    }

    let headers = {
        'Authorization': token,
        'x-request-id': _.get(req.context, 'headers.x-request-id')
    };

    let requests = [];
    let cache = {};

    Object.keys(clients).forEach(clientKey => {
        let client = Object.assign({ key: clientKey }, clients[clientKey]);
        let destinations = client.dsts;

        Object.keys(destinations).forEach(destinationKey => {
            let keyPath = [ 'tvm_tickets', _.snakeCase(destinationKey) ];
            let destination = Object.assign({ key: destinationKey }, destinations[destinationKey]);

            const ticketId = `${client.self_tvm_id}-${destination.dst_id}`;

            // чтобы не дублировать запросы для сервисов, работающих под одним tvm id
            // (таких как gendarme, fouras, setter)
            requests.push(
                (cache[ticketId] || (cache[ticketId] = fetchTicket(client, destination, headers)))
                    .then(ticket => _.set(req.context, keyPath, ticket))
            );
        });
    });

    return Promise.all(requests)
        .then(() => next())
        .catch(() => next());
}


function fetchTicket(client, destination, headers) {
    if (!client || !destination) {
        return Promise.reject();
    }

    let requestUrl = `${config.api.tvm}/tickets?src=${client.self_tvm_id}&dsts=${destination.dst_id}`;
    let options = {
        client: _.pick(client, [ 'key', 'self_tvm_id' ]),
        destination: _.pick(destination, [ 'key', 'dst_id' ])
    };

    return log(fetch)(requestUrl, { method: 'get', headers })
        .then(response => response.json())
        .then(response => {
            log('Picked TVM service ticket', options);
            return _.get(response, [ destination.key, 'ticket' ]);
        })
        .catch(() => {
            log('@error Failed to pick TVM service ticket', options);
        });
}
