const urlUtil = require('url');
const _ = require('lodash');
const sendHandledRequest = require('../lib/sendHandledRequest');
const logger = require('../lib/logger');
const config = require('../config');

const PROXIED_PROPS = [
    'auth', 'tvm_tickets', 'state', 'session', 'sessions', 'error', 'karma',
];

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

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

function fetchProxyAuthData(req, res, next) {
    const domain = {
        proxy: getDomain(config.api.tvm),
        current: getDomain(`${req.protocol}://${req.hostname}`),
    };

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

        logger.warn(message, req, domain);
    }

    if (!req.cookies.Session_id) {
        logger.warn('\'Session_id\' cookie is missing', req);
    }

    const requestOptions = {
        method: 'get',
        url: config.api.tvm,
        headers: {
            Cookie: Object.entries(req.cookies).map(pair => pair.join('=')).join('; '),
            'x-request-id': req.context.headers['x-request-id'],
        },
        source: req,
        noTrailingSlash: true,
    };

    return sendHandledRequest(requestOptions)
        .then(data => {
            req.context = _.merge(data, req.context);
            next();
        })
        .catch(() => next());
}

module.exports = {
    renderProxyAuthData,
    fetchProxyAuthData,
};
