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

module.exports = {
    proxyAuthData, pickAuthData
};

const PROXIED_PROPS = ['headers', 'session', 'tvm_tickets'];

function proxyAuthData(req, res, next) {
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify(_.pick(req.context, PROXIED_PROPS)));
}

function pickAuthData(req, res, next) {
    if (req.context.headers['X-Ya-User-Ticket'])
        return next();

    let domain = {
        proxy: getDomain(config.api.tvm),
        current: getDomain(req.protocol + '://' + req.hostname)
    };

    if (domain.proxy !== domain.current) {
        log(`@warning Cookies from your current domain '${domain.current}' may fail to match the authentication proxy domain '${domain.proxy}'`);
    }

    if (!req.cookies['Session_id'])
        log('@error \'Session_id\' cookie is missing');

    let headers = {
        Cookie: `Session_id=${req.cookies['Session_id']}`,
        'x-request-id': req.context.headers['x-request-id']
    };

    return log(fetch)(config.api.tvm, { headers })
        .then(response => response.json())
        .then(data => {
            req.context = _.merge(data, req.context);
            next();
        })
        .catch(() => next());
}

function getDomain(url) {
    return (String(urlUtil.parse(url).hostname).match(/\.[^\.]+(\.com)?\.\w+$/) || [])[0];
}
