const { URL } = require('url');
const _cloneDeep = require('lodash/cloneDeep');
const getRandomString = require('@connect/random-string');
const frameAncestors = require('../config/csp_frame_ancestors');

module.exports = () => (req, res, next) => {
    if (!req.accepts('html')) {
        return next();
    }

    let { config, cookies } = req;
    let csp = _cloneDeep(config.csp.rules);
    let nonce = getRandomString(12);

    if (config.csp.extra) {
        Object
            .entries(config.csp.extra)
            .forEach(([key, value]) => {
                if (csp[key]) {
                    csp[key] += ` ${value}`;
                } else {
                    csp[key] = value;
                }
            });
    }

    csp['script-src'] += ` 'nonce-${nonce}'`;

    if (csp['frame-ancestors']) {
        config.frameAncestors = csp['frame-ancestors'].split(' ');
    } else {
        csp['frame-ancestors'] = frameAncestors.join(' ');
        config.frameAncestors = frameAncestors;
    }

    let reportUrl = new URL(config.csp.report);

    reportUrl.searchParams.set('from', 'connect');
    reportUrl.searchParams.set('version', config.app.version);
    reportUrl.searchParams.set('yandex_login', cookies.yandex_login);
    reportUrl.searchParams.set('yandexuid', cookies.yandexuid);

    csp['report-uri'] = reportUrl.href;

    res.set('Content-Security-Policy', Object.entries(csp).map(([k, v]) => `${k} ${v}`).join('; '));
    req.nonce = nonce;

    next();
};
